Showing posts with label time. Show all posts
Showing posts with label time. Show all posts

Tuesday, March 27, 2012

@@FETCH_STATUS Reset

Sorry if this is a dumb question, but I am new to SQL Server and trying a simple cursor. Works fine the first time I execute, but then @.@.Fetch_Status stays at -1 and it will not work again. If I disconnect and then connect it will work once again. What I am doing wrong?

declare @.entityid int, @.datafrom nvarchar (255),

@.datato nvarchar (255), @.updatedate datetime

declare statustime1 cursor

local scroll static

for

select audit.entityid, audit.datafrom, audit.datato, audit.updatedate

from audit

, orders

where audit.entityid = orders.orderid

and audit.entitytypeid = 4

order by orders.orderid, audit.updatedate desc

open statustime1

While @.@.fetch_status = 0

Begin

fetch next from statustime1

into @.entityid, @.datafrom, @.datato, @.updatedate

print @.entityid

end

close statustime1

deallocate statustime1

go

The main thing that you are doing 'wrong' is using a CURSOR.

SQL Server operates most efficiently handling SET based data. (NOT row-wise data). A major mistake for most developers is keeping the 'recordset' mindset.

CURSORS are considered by some to be 'evil incarnate', whereas others recognize that there is a very small and highly limited use for them.

Most likely, your operation can be handled in a single set based query, with orders of magnitude imporvements in speed and reduced blocking.

If you want to post what you are attempting to accomplish, we may be able to better direct you to a set base solution.

But the main thing to understand is that in your learning, avoid using CURSORs. Push yourself to master set based logic. You will be much happier with the results.

|||

Thanks very much. I need to calculate the number of business days between two status events. Each is recorded in a row in the table, eg,

Order Event1 Date

1 Open June 1

1 Hold June 10

1Close June 30

2 Open July 1

2 hold July 10

I plan to fetch a row, save the values, fetch another row and calculate the days, continuining unitl a change in order and write output accordingly.

If you can suggest a set based approach I am all for it, however can anyone tell me why the @.@.fetch_status is not being reset.

|||

There are a few 'tools' that make the DBA's job much simplier. One of those tools is have a Calendar table in the database.

With a Calendar table, it is simple to JOIN against other tables with date values and derive the span of time between such dates. You may explore using a Calendar table with this resource.

With a Calendar table, you can easily meet your requiremens with a single query.

You need a FETCH before the WHILE statement. And then normally, the FETCH inside the loop is the last line -not the first line.

|||

I actually have a time dimension table so that will be a help, but can you show how we can get the data to do the subtraction between the two dates using set based approach. The trick is bringing together two rows that follow each other in sequence for the same order. I can't figure how to JOIN to do that.

I agree on fetch first outside the loop and so on, but that does not help with the question. Why does @.@.fetch_status still have a -1 even after the close and deallocate? It only seems to reset when I disconnect and that can't be right.

Thanks,

|||

You can use the function to fetch this data..

Sample.,

Code Snippet

Create function dbo.TotalBusinessDays

(

@.Start datetime,

@.End Datetime

)

returns int

as

Begin

Declare @.Result as int;

Set @.Result = 0;

While @.Start<=@.End

Begin

Select @.Result = @.Result + Case When datepart(weekday,@.Start) in (1,7) Then 0 Else 1 End

Set @.Start = @.Start + 1

End

return @.Result;

End

Go

Code Snippet

Create Table #events (

[Order] int ,

[Event1] Varchar(100) ,

[Date] datetime

);

Insert Into #events Values('1','Open','June 1 2007');

Insert Into #events Values('1','Hold','June 10 2007');

Insert Into #events Values('1','Close','June 30 2007');

Insert Into #events Values('2','Open','July 1 2007');

Insert Into #events Values('2','hold','July 10 2007');

Select

[Order]

,dbo.TotalBusinessDays([Open],[Hold]) OpenToHold

,dbo.TotalBusinessDays([Hold],[Close]) HoldToClose

From

(

Select

[Order]

, Max(case when [Event1] = 'Open' Then [Date] end) as [Open]

, Max(case when [Event1] = 'Hold' Then [Date] end) as [Hold]

, Max(case when [Event1] = 'Close' Then [Date] end) as [Close]

from

#events

Group bY

[Order]

) as Data

|||

I am impressed, looks pretty good. I may have oversimplied the example however,so how would it work for this data?

Order Event1 Date

3 Open July 1

3 Hold July 10

3 open july 20

3 hold Aug 1

3 open Aug 3

3 fill Aug 20

And I still would like to know why @.@.fetch_status stays -1 after I close and even deallocate the cursor.

|||

@.@.FETCH_STATUS is similar to a static variable with connection scope.

It holds the last know value.

If you try this, in a new connection window, without a CURSOR:

SELECT @.@.FETCH_STATUS

It will return [ 0 ].

It will reset on the next execution of FETCH.

|||

Bingo! You just solved it for me. I was being dense, and I was missing the point that @.@.fetch_status resets on the execution of fetch. It is not reset on open cursor. So I really need the first fetch outside the while loop and problem solved! My confusion is I am too familiar with that other DB (evil DB2) where SQLCODE would be zero after the open (lol) ..

Very interesting discussion and if you can think of set process approach to handle the more general case of multiple status changes during the order I would love to hear it.

|||

Here another sample,

Code Snippet

Create Table #orders (

[Order] int ,

[Event1] Varchar(100) ,

[Date] datetime

);

Insert Into #orders Values('3','Open','July 1 2007');

Insert Into #orders Values('3','Hold','July 10 2007');

Insert Into #orders Values('3','open','july 20 2007');

Insert Into #orders Values('3','hold','Aug 1 2007');

Insert Into #orders Values('3','open','Aug 3 2007');

Insert Into #orders Values('3','fill','Aug 20 2007');

Select * into #temp from #orders order By 1,3

Alter table #temp Add RowId int Identity(1,1)

select

[Pre].[Order],

[Pre].[Event1] +' to ' + [Post].[Event1],

dbo.TotalBusinessDays([Pre].[Date],[Post].[Date])

from

#temp [Pre]

Join #temp [Post] on [Pre].RowId = [Post].RowId-1

|||Since everyone was so nice to tell you why cursors are bad and give alternatives, and no one has answered your question:

The problem with your code is you need to change it to:

open statustime1

fetch next from statustime1

While @.@.fetch_status = 0

Begin

print @.entityid

fetch next from statustime1

into @.entityid, @.datafrom, @.datato, @.updatedate

end

In your current code you never did a fetch, so @.@.fetch_status is uninitiallized.

|||

Actually Tom, I think that I did answer that question.

Arnie Rowland wrote:

You need a FETCH before the WHILE statement. And then normally, the FETCH inside the loop is the last line -not the first line.

And

Arnie Rowland wrote:

@.@.FETCH_STATUS is similar to a static variable with connection scope.

It holds the last know value.

...

It will reset on the next execution of FETCH.

|||I am sorry Arnie, I miss that one. :< You did answer the question.

@@ERROR in mult thread environment?

Hi all,
I would like know if I can use @.@.ERROR to error in mult thread environment?
For sample:
If this SP is executed by 2 threads in same time, I wiil have correct value
in @.@.ERROR
Thanks
IF EXISTS (SELECT name
FROM sysobjects
WHERE name = N'terminal_ativo_sp'
AND type = 'P')
DROP PROCEDURE terminal_ativo_sp
GO
CREATE PROCEDURE terminal_ativo_sp
@.tid uterminalid,
@.ret INT OUTPUT
WITH ENCRYPTION
AS
BEGIN
-- declare vars
-- ----
--
DECLARE @.ativo BIT
-- init vars (assume SYS ERROR)
-- ----
--
SET @.ret = 101
SET @.ativo = 0
-- do work
-- ----
--
SELECT @.ativo = ativo FROM estabelecimentos_terminais WHERE terminal_id =
@.tid
-- check error
-- ----
--
IF (@.@.ERROR <> 0)
BEGIN
SET @.ret = 1
RETURN
END
-- check @.ativo
-- ----
--
IF (@.ativo = 1)
BEGIN
SET @.ret = 0
RETURN
END
ENDIts specific to the database connection and is not affected by any other
connection.
So, yes your code is fine.
Tony.
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials
"ReTF" <re.tf@.newsgroup.nospam> wrote in message
news:uAcEXet5FHA.1276@.TK2MSFTNGP09.phx.gbl...
> Hi all,
> I would like know if I can use @.@.ERROR to error in mult thread
> environment?
> For sample:
> If this SP is executed by 2 threads in same time, I wiil have correct
> value in @.@.ERROR
> Thanks
>
> IF EXISTS (SELECT name
> FROM sysobjects
> WHERE name = N'terminal_ativo_sp'
> AND type = 'P')
> DROP PROCEDURE terminal_ativo_sp
> GO
> CREATE PROCEDURE terminal_ativo_sp
> @.tid uterminalid,
> @.ret INT OUTPUT
> WITH ENCRYPTION
> AS
> BEGIN
> -- declare vars
> -- ----
--
> DECLARE @.ativo BIT
> -- init vars (assume SYS ERROR)
> -- ----
--
> SET @.ret = 101
> SET @.ativo = 0
> -- do work
> -- ----
--
> SELECT @.ativo = ativo FROM estabelecimentos_terminais WHERE terminal_id =
> @.tid
> -- check error
> -- ----
--
> IF (@.@.ERROR <> 0)
> BEGIN
> SET @.ret = 1
> RETURN
> END
> -- check @.ativo
> -- ----
--
> IF (@.ativo = 1)
> BEGIN
> SET @.ret = 0
> RETURN
> END
> END
>

Thursday, March 22, 2012

datetime Parameter issue

I'm using a sproc to insert the time (Now()) into a datetime field. Somehow the time "seconds" are not making it into the field. For example, the variable grabs the value of Now() - "9/16/2005 01:58:15 AM" to insert into the field. But when I view the records, the datetime value is "2005-09-16 13:58:00.000".
What am I doing wrong?
Thanks for your help!
Lynnette
Here is a snippet of the code and the sproc:

Dim recDateAs DateTime = Now()
cmd.Parameters.Add(New SqlParameter("@.DELastChg", SqlDbType.DateTime)).Value = recDate

ALTER PROC usp_AddTmpFLSAfromPT
@.dtWdate datetime,
@.whereString as varchar(255),
@.DEuser as varchar(30),
@.DELastChg datetime

AS

DECLARE @.strSQL as varchar(2000)

SET @.strSQL =
'
INSERT INTO tmpFLSAEmpInfo
( Emp_Number,
PT_ID,
Emp_Division,
Emp_Dept,
--Emp_DeptInfo,
Emp_Supervisor,
Emp_Location,
Emp_Union,
Emp_SG,
Emp_Shift,
DEusername,
DELastChg,
WrkDate
)
SELECT
Employee2.Emp_Number,
Employee2.[ID],
Employee2.Division,
Employee2.Job_Dept_Code,
Employee2.Job_Supervisor,
Employee2.Loc_Name,
Employee2.[Union],
Employee2.Sched_Group,
Employee2.Shift,
''' + @.DEUser + ''',
''' + CONVERT(varchar, @.DELastChg) + ''',
''' + CONVERT(varchar, @.dtWdate) + '''

FROM Employee2
WHERE '
+ @.whereString

EXEC(@.strSQL)

You are prbly losing the seconds because of the conversion to varchar in your code above. Put in the size also. Perhaps something like this :CONVERT(varchar(20), @.dtWdate) might help.|||Thanks for the response! I tried your suggestion, but it had no effect - still losing the seconds. I tried using CONVERT(datetime, @.DELastChg, 131) but then I get an error that I cannot convert string to DATETIME. I am hopelessly stuck.
Any other suggestions?
Thanks!
Lynnette|||Changed it toCONVERT(varchar, @.DELastChg, 113) and it works!

Thursday, March 8, 2012

.Net Deployment ....

Hi everybody,

I want install the project in client side .. In installation time i want to access the my server .. How i can make the setup file to access the internet.. please help me.....

Thanks & Regards,

S.Sajan

Not only is that NOT a good idea, many users will have firewalls that may keep your installation from accessing the internet.

See my post to your previous question for information about remote and unattended installations.

Tuesday, March 6, 2012

.NET Client connecting to MSDE for the first time

Our app's connection string at most (currently all) client sites points to
Sql Server 7 or 2000 on a seperate machine.
We have one small client who is running MSDE. We tried to bring them up
today.
I cannot get a connection to the MSDE. I keep getting
"System.Data.SqlClient.SqlException: SQL Server does not exist or access
denied."
I removed user id and password and set Integrated Security to True in the
connection string.
Our existing FoxPro app has no problems seeing and using MSDE, the .Net
Client cannot. The MSDE is running on the same machine as the .NET client
and the existing FoxPro application.
The FoxPro app uses an ODBC connection which works.
I googled this and I am not coming up with anything.
Any suggestions?
hi Greg,
Greg Robinson wrote:
> "System.Data.SqlClient.SqlException: SQL Server does not exist or
> access denied."
>
this kind of exception is a generic MDAC raised exception
please have a look at
http://support.microsoft.com/default...06&Product=sql
to see further suggestions..
Andrea Montanari (Microsoft MVP - SQL Server)
http://www.asql.biz/DbaMgr.shtmhttp://italy.mvps.org
DbaMgr2k ver 0.14.0 - DbaMgr ver 0.59.0
(my vb6+sql-dmo little try to provide MS MSDE 1.0 and MSDE 2000 a visual
interface)
-- remove DMO to reply

Sunday, February 19, 2012

.BAK extension ?

Hi !
Usualy I do not use SQL server, but this time I have got some data to
import. Data is on the CD, and it is named with extension .BAK. The
organization I've got data from does not have true DBA at this moment,
and I am not sure what I actualy got. The previous DBA resigned. I have
requested dump of database structure only, but I could manage with full
database dump, too. I am afraid that the file I've got is not either of
those two.
Currently I do not have SQL server installed.
Could .BAK files be interchanged between different machines ?
Could .BAK be an incremental backup ?
Are they compatibile for different versions of SQL server ?
Person that gave me the CD was not able to tell what version of SQL
server are they running.
DG.BAK is the standard extension for a full backup. You'll have to have a
recent version of SQL Server to try and restore it. If it restores OK, you
can extract the structure in the form of a script.
Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinpub.com
.
"Drazen Gemic" <anyone@.anywhere.tk> wrote in message
news:dv7haf$me7$1@.magcargo.vodatel.hr...
Hi !
Usualy I do not use SQL server, but this time I have got some data to
import. Data is on the CD, and it is named with extension .BAK. The
organization I've got data from does not have true DBA at this moment,
and I am not sure what I actualy got. The previous DBA resigned. I have
requested dump of database structure only, but I could manage with full
database dump, too. I am afraid that the file I've got is not either of
those two.
Currently I do not have SQL server installed.
Could .BAK files be interchanged between different machines ?
Could .BAK be an incremental backup ?
Are they compatibile for different versions of SQL server ?
Person that gave me the CD was not able to tell what version of SQL
server are they running.
DG

.BAK extension ?

Hi !
Usualy I do not use SQL server, but this time I have got some data to
import. Data is on the CD, and it is named with extension .BAK. The
organization I've got data from does not have true DBA at this moment,
and I am not sure what I actualy got. The previous DBA resigned. I have
requested dump of database structure only, but I could manage with full
database dump, too. I am afraid that the file I've got is not either of
those two.
Currently I do not have SQL server installed.
Could .BAK files be interchanged between different machines ?
Could .BAK be an incremental backup ?
Are they compatibile for different versions of SQL server ?
Person that gave me the CD was not able to tell what version of SQL
server are they running.
DG.BAK is the standard extension for a full backup. You'll have to have a
recent version of SQL Server to try and restore it. If it restores OK, you
can extract the structure in the form of a script.
--
Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinpub.com
.
"Drazen Gemic" <anyone@.anywhere.tk> wrote in message
news:dv7haf$me7$1@.magcargo.vodatel.hr...
Hi !
Usualy I do not use SQL server, but this time I have got some data to
import. Data is on the CD, and it is named with extension .BAK. The
organization I've got data from does not have true DBA at this moment,
and I am not sure what I actualy got. The previous DBA resigned. I have
requested dump of database structure only, but I could manage with full
database dump, too. I am afraid that the file I've got is not either of
those two.
Currently I do not have SQL server installed.
Could .BAK files be interchanged between different machines ?
Could .BAK be an incremental backup ?
Are they compatibile for different versions of SQL server ?
Person that gave me the CD was not able to tell what version of SQL
server are they running.
DG

.BAK extension ?

Hi !
Usualy I do not use SQL server, but this time I have got some data to
import. Data is on the CD, and it is named with extension .BAK. The
organization I've got data from does not have true DBA at this moment,
and I am not sure what I actualy got. The previous DBA resigned. I have
requested dump of database structure only, but I could manage with full
database dump, too. I am afraid that the file I've got is not either of
those two.
Currently I do not have SQL server installed.
Could .BAK files be interchanged between different machines ?
Could .BAK be an incremental backup ?
Are they compatibile for different versions of SQL server ?
Person that gave me the CD was not able to tell what version of SQL
server are they running.
DG
..BAK is the standard extension for a full backup. You'll have to have a
recent version of SQL Server to try and restore it. If it restores OK, you
can extract the structure in the form of a script.
Tom
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinpub.com
..
"Drazen Gemic" <anyone@.anywhere.tk> wrote in message
news:dv7haf$me7$1@.magcargo.vodatel.hr...
Hi !
Usualy I do not use SQL server, but this time I have got some data to
import. Data is on the CD, and it is named with extension .BAK. The
organization I've got data from does not have true DBA at this moment,
and I am not sure what I actualy got. The previous DBA resigned. I have
requested dump of database structure only, but I could manage with full
database dump, too. I am afraid that the file I've got is not either of
those two.
Currently I do not have SQL server installed.
Could .BAK files be interchanged between different machines ?
Could .BAK be an incremental backup ?
Are they compatibile for different versions of SQL server ?
Person that gave me the CD was not able to tell what version of SQL
server are they running.
DG

Thursday, February 16, 2012

**kill process**

Hi
In SQL 2000, sometimes it takes a long time to fetch data from a very
simple table that in normal cicumestances I can get the information in a
glance. and when I take look at
(enterprise manager->management->current activity->locks/process id)
I'll find some spids with red icon in blocking mode, so by right clicking
and killing the process I can get ride of them.
and I 've found in lock/objects when I have a view or procedure which is
locked all its tables are locked too.
I want to know when this problem occure and why? how can I prevent any
locking?
or how can I be informed when a lock object happened to go and kill
it?(should I accidently discover it?)
any help on this issue would be appreciated.M
http://www.sql-server-performance.c...ucing_locks.asp
"M" <rez1824@.yahoo.co.uk> wrote in message
news:op.tf7puxfcn9ig5y@.system109.parskhazar.net...
> Hi
> In SQL 2000, sometimes it takes a long time to fetch data from a very
> simple table that in normal cicumestances I can get the information in a
> glance. and when I take look at
> (enterprise manager->management->current activity->locks/process id)
> I'll find some spids with red icon in blocking mode, so by right clicking
> and killing the process I can get ride of them.
> and I 've found in lock/objects when I have a view or procedure which is
> locked all its tables are locked too.
> I want to know when this problem occure and why? how can I prevent any
> locking?
> or how can I be informed when a lock object happened to go and kill
> it?(should I accidently discover it?)
> any help on this issue would be appreciated.

Monday, February 13, 2012

**** grouping

hey peeps

well ive been stuck on this for a long time ... if anyone can help, i would appreciate it very much ....

in the database where im getting the data from, the data is displayed in the following way:

PART_ID PART_NAME PROD_TYPE DESC PASS_TYPE PASS_CNT
-----------------------------
4 BERT 5 CASH 0 15
6 BORO 5 CASH 0 1
6 BORO 5 CASH 3 4
etc
etc

here's my problem. when i try and display this in crystal, i group it by part_id and by prod_type but i still get two rows for CASH ...
example:

PRODUCT OPERATOR ADULT YOUTH
---------------------------
5 (CASH) 6 (PART_ID) 1 (PASS_COUNT)
5 (CASH) 6 (PART_ID) 4 PASS_COUNT

So what im trying to do is basically display it in one row....
NOW, ideally i want the above to be like this:

PRODUCT OPERATOR ADULT YOUTH
--------------------------
5 (CASH) 6 (PART_ID) 1 (PASS_COUNT) 4 PASS_COUNT

can anyone help ....
thanksK.
Lemme try this.

Firstly, if PASS_COUNT is a sumable value, it'll b a somewhat easier solution.
Make a formula field on your report that sums the pass_cnt field.
then place that field into the place of the other field.

Otherwise you can just make a sumed result set in your sql.
like

select ....,
sum(pass_cnt)
from <table>
where <conditions>
group by part_id,
part_name,
prod_type,
desc

but remember to leave out pass_type and pass_cnt. That is to elimenate the multiple rows.

Hope this helps somewhat.