Thursday, March 29, 2012
Cursor versus While Loop
Thanks!!The short answer boils down to both options are bad, and you are correct that the WHILE/SELECT/DELETE choice is even worse than the cursor.
More than 99 percent of the time there is a set-based solution that is hundreds or thousands of times faster/better than any loop can be, so the set based solution is what should be your "holy grail". Fix the problem instead of trying to find ways to make the loop less of an annoyance!
-PatP|||Why don't you post what it is you're trying to dosql
Cursor Update problem
or update another table. I am using a while loop to fetch all the vaules
from the cursor and then I close and deallocate the cursor. Everything runs
fine the first time but when I run the procedure again it updates the first
record with the information from the last record process from the time
before. If it helps I am running it as a job just like it will run when
completed. Ideas on why I am getting data from the previous run?Can you poste the code instead just a brief description of the problem?
Please provide DDL and sample data.
http://www.aspfaq.com/etiquette.asp?id=5006
AMB
"Shannon Thompson" wrote:
> I am using a cursor to take information from a temp table and either inser
t
> or update another table. I am using a while loop to fetch all the vaules
> from the cursor and then I close and deallocate the cursor. Everything ru
ns
> fine the first time but when I run the procedure again it updates the firs
t
> record with the information from the last record process from the time
> before. If it helps I am running it as a job just like it will run when
> completed. Ideas on why I am getting data from the previous run?|||Here is my code but I cannot give you the code for stored procedures call
from this code here because they are Encrypted and part of the software
program I am integrating with.
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[xxx]')
and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[xxx]
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE procedure xxxx
AS
/*
** Declare & initialize Local Variables
***
*/
DECLARE @.iReturnCode int,
@.iRet int,
@.vchFirstName nvarchar(255) ,
@.vchLastName nvarchar(255) ,
@.vchAdSource nvarchar(255) ,
@.vchOnyxCode nvarchar(255) ,
@.vchAddress1 nvarchar(255) ,
@.vchCity nvarchar(255) ,
@.chStateCode nvarchar(50) ,
@.vchPostCode nvarchar(40) ,
@.chCountryCode nvarchar(50) ,
@.vchPhoneType nvarchar(50) ,
@.vchPhoneNumber nvarchar(40) ,
@.vchBestTime nvarchar(255),
@.vchEmail nvarchar(255),
@.iHt_Feet nvarchar(50),
@.iHt_Inches nvarchar(50),
@.iWeight nvarchar(50),
@.dtDOB nvarchar(50),
@.vchInsurance nvarchar(255),
@.vchOtherIns nvarchar(255),
@.vchInsuranceType nvarchar(255),
@.vchSem nvarchar(255),
@.vchSemSrc nvarchar(255),
@.dtTimeStamp nvarchar(255),
@.iIndividualId int ,
@.iIncidentId int,
@.onyx_cursor cursor,
@.chInsUpd nchar(1),
@.iPhoneTypeId int,
@.getDate datetime,
@.dtPreviousUpdateDate datetime,
@.iHeight int,
@.dtUpdate datetime,
@.bmi float
set @.iReturnCode = 0
set @.iRet = 0
set @.getDate = getDate()
set @.bmi = 0
set @.onyx_cursor = cursor
--local Scroll Keyset Optimistic
FOR Select
vchFirstName,
vchLastName,
vchAdSource,
vchOnyxCode,
vchAddress1,
vchCity,
chStateCode,
vchPostCode,
chCountryCode,
vchPhoneType,
vchPhoneNumber,
vchBestTime,
vchEmail,
iHt_Feet,
iHt_Inches,
iWeight,
dtDOB,
vchInsurance,
vchOtherIns,
vchInsuranceType,
vchSem,
vchSemSrc,
dtTimeStamp
from CallCenter_Temp
OPEN @.onyx_cursor
FETCH NEXT from @.onyx_cursor into
@.vchFirstName,
@.vchLastName,
@.vchAdSource,
@.vchOnyxCode,
@.vchAddress1,
@.vchCity,
@.chStateCode,
@.vchPostCode,
@.chCountryCode,
@.vchPhoneType,
@.vchPhoneNumber,
@.vchBestTime,
@.vchEmail,
@.iHt_Feet,
@.iHt_Inches,
@.iWeight,
@.dtDOB,
@.vchInsurance,
@.vchOtherIns,
@.vchInsuranceType,
@.vchSem,
@.vchSemSrc,
@.dtTimeStamp
-- loop while there are still records in table
WHILE @.@.FETCH_STATUS = 0
BEGIN
set @.iHeight= convert(int,convert(float,ROUND(@.iHt_Inc
hes,0)) +
(convert(float,ROUND(@.iHt_Feet,0))*12))
IF @.iHeight <> 0 AND @.iWeight <> 0
BEGIN
declare @.meters float,
@.totalinches float,
@.kilos float,
@.metersq float
set @.totalinches = convert(float,@.iHeight)
set @.meters = @.totalinches/39.36
set @.kilos = convert(float,@.iWeight)/2.2
set @.metersq = @.meters * @.meters
set @.bmi = Round(@.kilos/@.metersq,0)
END
set @.vchFirstName = UPPER(@.vchFirstName)
set @.vchLastName = UPPER(@.vchLastName)
set @.vchAddress1 = UPPER(@.vchAddress1)
set @.vchCity = UPPER(@.vchCity)
set @.chStateCode = UPPER(@.chStateCode)
set @.chCountryCode = UPPER(@.chCountryCode)
-- determine phone type
SELECT @.iPhoneTypeId =
CASE LOWER(RTRIM(@.vchPhoneType))
WHEN 'home' THEN 119
WHEN 'cell' THEN 103
WHEN 'work' THEN 102
ELSE 119
END
-- if no Onyx Id is listed then search for the individual
IF @.iIndividualId is null
BEGIN
-- check to see if Person is in Onyx
exec @.iRet = wbocpscOnyxTalley
@.vchFirstName,
@.vchLastName,
@.vchAddress1,
@.vchCity,
@.chStateCode,
@.vchPostCode,
NULL
if (@.iRet <> 0)
begin
--update
set @.chInsUpd = 'U'
set @.iIndividualId = @.iRet
end
else
begin
--insert
set @.chInsUpd = 'I'
end
end
-- iIndividualId is given so this is an update
ELSE
BEGIN
set @.chInsUpd = 'U'
END
print @.chInsUpd + ' ' + @.vchLastName
if @.chInsUpd = 'I'
begin
exec @.iReturnCode = wbospsiIndividual
1,
@.iIndividualId,
'ENG',
'PatientLC',
null,
@.vchFirstName,
null,
@.vchLastName,
null,
@.vchAddress1,
null,
null,
@.vchCity,
@.chStateCode,
@.chCountryCode,
@.vchPostCode,
@.vchPhoneNumber,
@.vchEmail,
'',
null,
null,
null,
0,
'',
'',
'',
null,
null,
@.iPhoneTypeId,
119,
null,
null,
1,
1,
0,
null,
null,
@.iHeight,
@.iWeight,
@.bmi,
null,
null,
null,
@.dtDOB,
null,
'CCLeads',
@.getDate,
0,
1,
1
if @.iReturnCode <> 0
begin
print 'insert failed for ' + @.vchFirstName + ' ' + @.vchLastName
print @.iReturnCode
end
else
begin
print 'inserted ' + @.vchFirstName + ' ' + @.vchLastName
print @.iReturnCode
end
end
ELSE
begin
select @.dtPreviousUpdateDate = dtUpdateDate FROM Individual WHERE
iIndividualId = @.iIndividualId
exec @.iReturnCode = ospsgCheckRecordLock
@.dtUpdate OUTPUT,
@.dtPreviousUpdateDate,
1
-- if error returned then must change dtUpdateDate to current
if (@.iReturnCode <> 0)
begin
UPDATE Individual SET dtUpdateDate = @.getDate,chUpdateBy='sa' WHERE
iIndividualId = @.iIndividualId
exec @.iReturnCode = wbospsuIndividual
1,
@.iIndividualId,
'ENG',
'PatientLC',
null,
@.vchFirstName,
null,
@.vchLastName,
null,
@.vchAddress1,
null,
null,
@.vchCity,
@.chStateCode,
@.chCountryCode,
@.vchPostCode,
@.vchPhoneNumber,
@.vchEmail,
'',
null,
null,
null,
0,
'',
'',
'',
null,
null,
@.iPhoneTypeId,
null,
null,
null,
1,
1,
0,
null,
null,
null,
@.iHeight,
@.iWeight,
@.bmi,
null,
null,
@.dtDOB,
null,
'CCLeads',
@.getDate,
0,
1
if @.iReturnCode <> 0
begin
print 'update failed for ' + @.vchFirstName + ' ' + @.vchLastName
print @.iReturnCode
end
else
begin
print 'updated ' + @.vchFirstName + ' ' + @.vchLastName
print @.iReturnCode
end
end
end
--fetch next record
FETCH NEXT from @.onyx_cursor into
@.vchFirstName,
@.vchLastName,
@.vchAdSource,
@.vchOnyxCode,
@.vchAddress1,
@.vchCity,
@.chStateCode,
@.vchPostCode,
@.chCountryCode,
@.vchPhoneType,
@.vchPhoneNumber,
@.vchBestTime,
@.vchEmail,
@.iHt_Feet,
@.iHt_Inches,
@.iWeight,
@.dtDOB,
@.vchInsurance,
@.vchOtherIns,
@.vchInsuranceType,
@.vchSem,
@.vchSemSrc,
@.dtTimeStamp
END
CLOSE @.onyx_cursor
DEALLOCATE @.onyx_cursor
return @.iReturnCode
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
"Alejandro Mesa" wrote:
> Can you poste the code instead just a brief description of the problem?
> Please provide DDL and sample data.
> http://www.aspfaq.com/etiquette.asp?id=5006
>
> AMB
> "Shannon Thompson" wrote:
>|||Shannon,
The cursor is based on a permanent table. How are you feeding this table
before calling the sp?
AMB
"Shannon Thompson" wrote:
> Here is my code but I cannot give you the code for stored procedures call
> from this code here because they are Encrypted and part of the software
> program I am integrating with.
> if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[xxx]')
> and OBJECTPROPERTY(id, N'IsProcedure') = 1)
> drop procedure [dbo].[xxx]
> GO
> SET QUOTED_IDENTIFIER OFF
> GO
> SET ANSI_NULLS OFF
> GO
>
> CREATE procedure xxxx
> AS
> /*
> ** Declare & initialize Local Variables
> ***
> */
>
> DECLARE @.iReturnCode int,
> @.iRet int,
> @.vchFirstName nvarchar(255) ,
> @.vchLastName nvarchar(255) ,
> @.vchAdSource nvarchar(255) ,
> @.vchOnyxCode nvarchar(255) ,
> @.vchAddress1 nvarchar(255) ,
> @.vchCity nvarchar(255) ,
> @.chStateCode nvarchar(50) ,
> @.vchPostCode nvarchar(40) ,
> @.chCountryCode nvarchar(50) ,
> @.vchPhoneType nvarchar(50) ,
> @.vchPhoneNumber nvarchar(40) ,
> @.vchBestTime nvarchar(255),
> @.vchEmail nvarchar(255),
> @.iHt_Feet nvarchar(50),
> @.iHt_Inches nvarchar(50),
> @.iWeight nvarchar(50),
> @.dtDOB nvarchar(50),
> @.vchInsurance nvarchar(255),
> @.vchOtherIns nvarchar(255),
> @.vchInsuranceType nvarchar(255),
> @.vchSem nvarchar(255),
> @.vchSemSrc nvarchar(255),
> @.dtTimeStamp nvarchar(255),
> @.iIndividualId int ,
> @.iIncidentId int,
> @.onyx_cursor cursor,
> @.chInsUpd nchar(1),
> @.iPhoneTypeId int,
> @.getDate datetime,
> @.dtPreviousUpdateDate datetime,
> @.iHeight int,
> @.dtUpdate datetime,
> @.bmi float
> set @.iReturnCode = 0
> set @.iRet = 0
> set @.getDate = getDate()
> set @.bmi = 0
> set @.onyx_cursor = cursor
> --local Scroll Keyset Optimistic
> FOR Select
> vchFirstName,
> vchLastName,
> vchAdSource,
> vchOnyxCode,
> vchAddress1,
> vchCity,
> chStateCode,
> vchPostCode,
> chCountryCode,
> vchPhoneType,
> vchPhoneNumber,
> vchBestTime,
> vchEmail,
> iHt_Feet,
> iHt_Inches,
> iWeight,
> dtDOB,
> vchInsurance,
> vchOtherIns,
> vchInsuranceType,
> vchSem,
> vchSemSrc,
> dtTimeStamp
> from CallCenter_Temp
> OPEN @.onyx_cursor
> FETCH NEXT from @.onyx_cursor into
> @.vchFirstName,
> @.vchLastName,
> @.vchAdSource,
> @.vchOnyxCode,
> @.vchAddress1,
> @.vchCity,
> @.chStateCode,
> @.vchPostCode,
> @.chCountryCode,
> @.vchPhoneType,
> @.vchPhoneNumber,
> @.vchBestTime,
> @.vchEmail,
> @.iHt_Feet,
> @.iHt_Inches,
> @.iWeight,
> @.dtDOB,
> @.vchInsurance,
> @.vchOtherIns,
> @.vchInsuranceType,
> @.vchSem,
> @.vchSemSrc,
> @.dtTimeStamp
> -- loop while there are still records in table
> WHILE @.@.FETCH_STATUS = 0
> BEGIN
> set @.iHeight= convert(int,convert(float,ROUND(@.iHt_Inc
hes,0)) +
> (convert(float,ROUND(@.iHt_Feet,0))*12))
> IF @.iHeight <> 0 AND @.iWeight <> 0
> BEGIN
> declare @.meters float,
> @.totalinches float,
> @.kilos float,
> @.metersq float
> set @.totalinches = convert(float,@.iHeight)
> set @.meters = @.totalinches/39.36
> set @.kilos = convert(float,@.iWeight)/2.2
> set @.metersq = @.meters * @.meters
> set @.bmi = Round(@.kilos/@.metersq,0)
> END
> set @.vchFirstName = UPPER(@.vchFirstName)
> set @.vchLastName = UPPER(@.vchLastName)
> set @.vchAddress1 = UPPER(@.vchAddress1)
> set @.vchCity = UPPER(@.vchCity)
> set @.chStateCode = UPPER(@.chStateCode)
> set @.chCountryCode = UPPER(@.chCountryCode)
> -- determine phone type
> SELECT @.iPhoneTypeId =
> CASE LOWER(RTRIM(@.vchPhoneType))
> WHEN 'home' THEN 119
> WHEN 'cell' THEN 103
> WHEN 'work' THEN 102
> ELSE 119
> END
> -- if no Onyx Id is listed then search for the individual
> IF @.iIndividualId is null
> BEGIN
> -- check to see if Person is in Onyx
> exec @.iRet = wbocpscOnyxTalley
> @.vchFirstName,
> @.vchLastName,
> @.vchAddress1,
> @.vchCity,
> @.chStateCode,
> @.vchPostCode,
> NULL
> if (@.iRet <> 0)
> begin
> --update
> set @.chInsUpd = 'U'
> set @.iIndividualId = @.iRet
> end
> else
> begin
> --insert
> set @.chInsUpd = 'I'
> end
> end
> -- iIndividualId is given so this is an update
> ELSE
> BEGIN
> set @.chInsUpd = 'U'
> END
> print @.chInsUpd + ' ' + @.vchLastName
> if @.chInsUpd = 'I'
> begin
> exec @.iReturnCode = wbospsiIndividual
> 1,
> @.iIndividualId,
> 'ENG',
> 'PatientLC',
> null,
> @.vchFirstName,
> null,
> @.vchLastName,
> null,
> @.vchAddress1,
> null,
> null,
> @.vchCity,
> @.chStateCode,
> @.chCountryCode,
> @.vchPostCode,
> @.vchPhoneNumber,
> @.vchEmail,
> '',
> null,
> null,
> null,
> 0,
> '',
> '',
> '',
> null,
> null,
> @.iPhoneTypeId,
> 119,
> null,
> null,
> 1,
> 1,
> 0,
> null,
> null,
> @.iHeight,
> @.iWeight,
> @.bmi,
> null,
> null,
> null,
> @.dtDOB,
> null,
> 'CCLeads',
> @.getDate,
> 0,
> 1,
> 1
> if @.iReturnCode <> 0
> begin
> print 'insert failed for ' + @.vchFirstName + ' ' + @.vchLastName
> print @.iReturnCode
> end
> else
> begin
> print 'inserted ' + @.vchFirstName + ' ' + @.vchLastName
> print @.iReturnCode
> end
> end
> ELSE
> begin
> select @.dtPreviousUpdateDate = dtUpdateDate FROM Individual WHERE
> iIndividualId = @.iIndividualId
> exec @.iReturnCode = ospsgCheckRecordLock
> @.dtUpdate OUTPUT,
> @.dtPreviousUpdateDate,
> 1
> -- if error returned then must change dtUpdateDate to current
> if (@.iReturnCode <> 0)
> begin
> UPDATE Individual SET dtUpdateDate = @.getDate,chUpdateBy='sa' WHERE
> iIndividualId = @.iIndividualId
> exec @.iReturnCode = wbospsuIndividual
> 1,
> @.iIndividualId,
> 'ENG',
> 'PatientLC',
> null,
> @.vchFirstName,
> null,
> @.vchLastName,
> null,
> @.vchAddress1,
> null,
> null,
> @.vchCity,
> @.chStateCode,
> @.chCountryCode,
> @.vchPostCode,
> @.vchPhoneNumber,
> @.vchEmail,
> '',
> null,
> null,
> null,
> 0,
> '',
> '',
> '',
> null,
> null,
> @.iPhoneTypeId,
> null,
> null,
> null,|||This table (CallCenter_temp) is populated by another stored procedure that
gets a file list from a directory, puts that into a true temp table (gets
created and deleted within procedure) and batch inserts each text file:
BEGIN
/*
** Declare & initialize Local Variables
*/
DECLARE
@.iReturnCode int,
@.MyFile varchar(200),
@.SQL varchar(2000),
@.Path varchar(400),
@.onyx_cursor cursor,
@.vchFileName varchar(255),
@.vchXPCMD nvarchar(255)
select
@.iReturnCode = 0
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.tables WHERE table_name =
'CCFiles')
BEGIN
DROP TABLE CCFiles
END
CREATE TABLE [dbo].[CCFiles] (
[vchFileName] [nvarchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
SET @.Path = '\\wms1\c$\CallCenterWebSite\data'
EXECUTE cpListFiles @.Path,'CCFiles','%.txt',NULL,0
IF @.iReturnCode = 0
BEGIN
SET @.onyx_cursor = cursor
FOR SELECT
vchFileName
FROM CCFiles
OPEN @.onyx_cursor
FETCH NEXT from @.onyx_cursor into @.vchFileName
WHILE @.@.FETCH_STATUS = 0
BEGIN
SET @.SQL = 'BULK INSERT [Onyx]..CallCenter_temp FROM "' + @.Path +
@.vchFileName + '"' +
' WITH(BATCHSIZE = 250 ,DATAFILETYPE = "char" ,FIELDTERMINATOR = "|"
,ROWTERMINATOR = "\n",MAXERRORS = 50 ,TABLOCK)'
--SELECT @.SQL
EXECUTE (@.SQL)
IF @.iReturnCode = 0
BEGIN
set @.vchFileName = @.Path + @.vchFileName
set @.vchXPCMD = '@.Del ' + RTrim(@.vchFileName)
--execute master..xp_cmdshell @.vchXPCMD
END
FETCH NEXT from @.onyx_cursor into @.vchFileName
END
END
DROP TABLE CCFiles
return @.iReturnCode
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
"Alejandro Mesa" wrote:
> Shannon,
> The cursor is based on a permanent table. How are you feeding this table
> before calling the sp?
>
> AMB
> "Shannon Thompson" wrote:
>|||> I cannot give you the code for stored procedures call
> from this code here because they are Encrypted and part of the software
> program I am integrating with.
Personally I'd want to decrypt those procs to see if it's feasible to
rewrite your code without a cursor.
http://www.planetsourcecode.com/vb/...6J00S003GU.html
David Portas
SQL Server MVP
--|||Shannon,
In the previous post you are not closing and deallocating the cursor and
this cursor.
AMB
"Shannon Thompson" wrote:
> This table (CallCenter_temp) is populated by another stored procedure that
> gets a file list from a directory, puts that into a true temp table (gets
> created and deleted within procedure) and batch inserts each text file:
> BEGIN
> /*
> ** Declare & initialize Local Variables
> */
> DECLARE
> @.iReturnCode int,
> @.MyFile varchar(200),
> @.SQL varchar(2000),
> @.Path varchar(400),
> @.onyx_cursor cursor,
> @.vchFileName varchar(255),
> @.vchXPCMD nvarchar(255)
> select
> @.iReturnCode = 0
> IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.tables WHERE table_name =
> 'CCFiles')
> BEGIN
> DROP TABLE CCFiles
> END
> CREATE TABLE [dbo].[CCFiles] (
> [vchFileName] [nvarchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
> ) ON [PRIMARY]
> SET @.Path = '\\wms1\c$\CallCenterWebSite\data'
> EXECUTE cpListFiles @.Path,'CCFiles','%.txt',NULL,0
> IF @.iReturnCode = 0
> BEGIN
> SET @.onyx_cursor = cursor
> FOR SELECT
> vchFileName
> FROM CCFiles
> OPEN @.onyx_cursor
> FETCH NEXT from @.onyx_cursor into @.vchFileName
> WHILE @.@.FETCH_STATUS = 0
> BEGIN
> SET @.SQL = 'BULK INSERT [Onyx]..CallCenter_temp FROM "' + @.Path +
> @.vchFileName + '"' +
> ' WITH(BATCHSIZE = 250 ,DATAFILETYPE = "char" ,FIELDTERMINATOR = "|"
> ,ROWTERMINATOR = "\n",MAXERRORS = 50 ,TABLOCK)'
> --SELECT @.SQL
> EXECUTE (@.SQL)
> IF @.iReturnCode = 0
> BEGIN
> set @.vchFileName = @.Path + @.vchFileName
> set @.vchXPCMD = '@.Del ' + RTrim(@.vchFileName)
> --execute master..xp_cmdshell @.vchXPCMD
> END
> FETCH NEXT from @.onyx_cursor into @.vchFileName
> END
> END
> DROP TABLE CCFiles
> return @.iReturnCode
> END
>
> GO
> SET QUOTED_IDENTIFIER OFF
> GO
> SET ANSI_NULLS ON
> GO
>
>
> "Alejandro Mesa" wrote:
>|||The reason I use a cursor is that having limited SQL Stored Procedure
experience (mainly VBScript SQL experience) I know of no other way to go
record by record to call these stored procedures. I have de-crypted these
procedures but by using these stored procedures instead of recreating them I
can safety insert data into the database without breaking any middle tier
rules of the software and corrupt any of the data.
The store procedures are made to put one person at a time into the database
(when a users clicks save on the web page) not bulk so this is why I am usin
g
the cursor.
"David Portas" wrote:
> Personally I'd want to decrypt those procs to see if it's feasible to
> rewrite your code without a cursor.
> http://www.planetsourcecode.com/vb/...6J00S003GU.html
> --
> David Portas
> SQL Server MVP
> --
>|||Why did you destroy Standard SQL behavior? Why are there more NULLs in
one table than should be in an entire Fortune 500 accounting package?
Do you really have a lot of data elements that are in Chinese and 255
characters long? Why do you have data type prefixes on variable names,
which is a violation of both good programming and ISO-11179? Why do you
have numeric data elements in strings? What kind of total garbage are
trying to get with things like "weight VARCHAR(50)", "@.phonetype
VARCHAR(50)", etc. And you don't seem to be aware of floating
point rounding errors (does your machine have a floating point
processor, or do you want to slow things down with a software floating
point package?)
You keep height in inches or cm then convert it for display. You do
not do this in the database. The syntax for CAST is CAST (<exp> AS
<datatype> ) -- do not use the proprietary CONVERT().
You are NOT writing SQL at all, but some kind of 3GL, using SQL for it.
But even worse, you did absolutely no design or research on the data.
Other products have a MERGE or UPSERT statement to do this. The usual
pattern in older products is:
BEGIN
-- insert the new rows
INSERT INTO Foobar
SELECT *
FROM WorkingData AS W
WHERE W.keycol
NOT IN (SELECT keycol FROM Foobar);
-- update the rows are already there
UPDATE Foobar
SET <column>
= (SELECT col FROM WorkingData AS W
WHERE W.keycol = Foobar.keycol)
WHERE keycol IN (SELECT keycol FROM WorkingData);
END;|||Since you have no idea about the situation or the database schema your
posting is just wasted useless space. Please do not bother my thread again
unless you want to know more about the database and can actually just give m
e
a reason to my error. I did not ask for a comments on the coding though
constructive criticism, not code bashing, is appreciated - again I stated I
am a Computer Programmer using SQL code in ASP pages mostly not much done
with SQL Server, I would have done this in VBScript (which I have already
done before) but store procedures are more efficient and reliable.
Oh and the comment about doing design and research on the data, you have no
idea how much design and research in this database I have done. With a
database that all the stored procedures are encrypted (which you cannot
decrypt unless you want to break the software agreement which I play by the
rules maybe you do not), no manuals or references on the database (because i
t
is part of a software program and while they want you to add functionalilty
to the product for your own uses they are not forth coming with how to do
things) and myself being no where near a DBA I think I have a pretty good
understanding of this database which you clearly do not because you did not
ask!
Thanks but no Thanks for your post...this is why I originally did not post
the code because people like you want to just code bash instead of helping!
"--CELKO--" wrote:
> Why did you destroy Standard SQL behavior? Why are there more NULLs in
> one table than should be in an entire Fortune 500 accounting package?
> Do you really have a lot of data elements that are in Chinese and 255
> characters long? Why do you have data type prefixes on variable names,
> which is a violation of both good programming and ISO-11179? Why do you
> have numeric data elements in strings? What kind of total garbage are
> trying to get with things like "weight VARCHAR(50)", "@.phonetype
> VARCHAR(50)", etc. And you don't seem to be aware of floating
> point rounding errors (does your machine have a floating point
> processor, or do you want to slow things down with a software floating
> point package?)
> You keep height in inches or cm then convert it for display. You do
> not do this in the database. The syntax for CAST is CAST (<exp> AS
> <datatype> ) -- do not use the proprietary CONVERT().
> You are NOT writing SQL at all, but some kind of 3GL, using SQL for it.
> But even worse, you did absolutely no design or research on the data.
> Other products have a MERGE or UPSERT statement to do this. The usual
> pattern in older products is:
> BEGIN
> -- insert the new rows
> INSERT INTO Foobar
> SELECT *
> FROM WorkingData AS W
> WHERE W.keycol
> NOT IN (SELECT keycol FROM Foobar);
> -- update the rows are already there
> UPDATE Foobar
> SET <column>
> = (SELECT col FROM WorkingData AS W
> WHERE W.keycol = Foobar.keycol)
> WHERE keycol IN (SELECT keycol FROM WorkingData);
> END;
>
cursor to slow
set nocount on
Declare @.entry bigint, @.mobile int, @.fid int, @.rid int, @.pin char(10), @.commission tinyint,
@.barred tinyint, @.barred_acse tinyint, @.les char(10), @.mobile1 int, @.fid1 int,
@.rid1 int, @.pin1 char(10), @.commission1 tinyint, @.barred1 tinyint, @.barred_acse1 tinyint,
@.les1 char(10)
DECLARE changes CURSOR
FOR
select mobile, fid, rid, pin, commission, barred, barred_acse, les
from mobile_changes
OPEN changes
FETCH NEXT from changes
INTO @.mobile, @.fid, @.rid, @.pin, @.commission, @.barred, @.barred_acse, @.les
WHILE @.@.FETCH_STATUS = 0
BEGIN
DECLARE history CURSOR
FOR
select max(entry), mobile, fid, rid, pin, commission, barred, barred_acse, les
from mobile_history
where mobile = @.mobile
group by mobile, fid, rid, pin, commission, barred, barred_acse, les
OPEN history
FETCH NEXT FROM history
INTO @.entry, @.mobile1, @.fid1, @.rid1, @.pin1, @.commission1, @.barred1, @.barred_acse1, @.les1
IF (
@.mobile = @.mobile1 and @.fid = @.fid1 and @.rid = @.rid1 and @.pin = @.pin1 and
@.commission = @.commission1 and @.barred = @.barred1 and @.barred_acse = @.barred_acse1 and
@.les = @.les1)
BEGIN
DELETE FROM mobile_changes where mobile = @.mobile
END
CLOSE history
deallocate history
FETCH NEXT FROM changes
INTO @.mobile, @.fid, @.rid, @.pin, @.commission, @.barred, @.barred_acse, @.les
END
close changes
deallocate changesTo speed up your processing, you can avoid the cursors. Use temp table instead.
Try the following steps:
1. Create temp table from mobile_history with all required fields.
select max(a.entry) MaxEntry, a.mobile, a.fid, a.rid,
a.pin, a.commission, a.barred, a.barred_acse, a.les
into #temp_history
from mobile_history a, mobile_changes b
where a.mobile = b.mobile
group by mobile, fid, rid, pin, commission, barred, barred_acse, les
2. Delete records from the table mobile_changes using temp table.
delete mobile_changes
from mobile_changes a, #temp_history b
where a.mobile_no = b.mobile_no
and a.fid = b.fid
and a.rid = b.rid
and a.pin = b.pin
and a.commission = b.commission
and a.barred = b.barred
and a.barred_acse = b.barred_acse
and a.les = b.les
The above will do the same thing. Here, my only confusion is why do you need max(entry) in mobile_history table. Anyway, you are not using it anywhere. If i assume that u are not using it anywhere, our query can be even simpler. Just use the following query.
delete mobile_changes
from mobile_changes a, #mobile_history b
where a.mobile_no = b.mobile_no
and a.fid = b.fid
and a.rid = b.rid
and a.pin = b.pin
and a.commission = b.commission
and a.barred = b.barred
and a.barred_acse = b.barred_acse
and a.les = b.les
Thanks.
Prabhanjan|||The Entry field is a auto numbered primary key. The max(entry) returns the latest record grouped by mobile. Thanks for the help the cursor method was taking up to 50 minutes to complete, your method takes < 10 seconds.
Cursor to loop through all tables in db
I have a db with 285 tables. I want to add 1 varchar(10) column to all 285
tables called 'year' and I always want year to be '1999'.
I am struggling with setting up the cursor though. This is what I have so
far:
declare table_loop cursor
For select name from sysobjects where xtype = 'u'
open table_loop
Fetch table_loop
alter table [name]
add db_year varchar(10)
close table_loop
deallocate table_loop
go
Any help would be greatly appreciated.
Thanks.
ArcherIt has to be something like
declare @.name varchar(')
declare table_loop cursor for select name from sysobjects where xtype = 'u'
open table_loop
fetch next from table_loop into @.Name
while @.@.FETCH_STATUS = 0
begin
-- this migth have to be some dynamic thing, like:
-- exec 'alter table ' + @.name + ' add db_year varchar(10)'
alter table [@.name]
add db_year varchar(10)
fetch next from table_loop into @.name
end
close table_loop
deallocate table_loop
go
Kr.
Soren
"bagman3rd" <bagman3rd@.discussions.microsoft.com> skrev i en meddelelse
news:24C3F48A-4961-4285-9FDF-F790961789C5@.microsoft.com...
> So far, I have avoided using cursors, but I see no other way to do this.
> I have a db with 285 tables. I want to add 1 varchar(10) column to all
> 285
> tables called 'year' and I always want year to be '1999'.
> I am struggling with setting up the cursor though. This is what I have so
> far:
> declare table_loop cursor
> For select name from sysobjects where xtype = 'u'
> open table_loop
> Fetch table_loop
> alter table [name]
> add db_year varchar(10)
> close table_loop
> deallocate table_loop
> go
> Any help would be greatly appreciated.
> Thanks.
> Archer|||HI
There is a straight forward method for this
google for undocumented sp_Msforeachtable command
Regards
R.D
"Soeren S. Joergensen" wrote:
> It has to be something like
> declare @.name varchar(')
> declare table_loop cursor for select name from sysobjects where xtype = 'u
'
> open table_loop
> fetch next from table_loop into @.Name
> while @.@.FETCH_STATUS = 0
> begin
> -- this migth have to be some dynamic thing, like:
> -- exec 'alter table ' + @.name + ' add db_year varchar(10)'
> alter table [@.name]
> add db_year varchar(10)
> fetch next from table_loop into @.name
> end
> close table_loop
> deallocate table_loop
> go
> Kr.
> Soren
> "bagman3rd" <bagman3rd@.discussions.microsoft.com> skrev i en meddelelse
> news:24C3F48A-4961-4285-9FDF-F790961789C5@.microsoft.com...
>
>|||Wouldn't you be better off with a DDL script that you can check into source
control and deploy to test and live environments? Try this:
SELECT
'ALTER TABLE '+QUOTENAME(table_schema)+'.'+QUOTENAME(table_name)+
' ADD [year_num] VARCHAR(10) NOT NULL'+
' CONSTRAINT [df_year_num] DEFAULT (''1999'')'
FROM information_schema.tables ;
Output as text and you have your script.
Note that "YEAR" is a reserved word so not a good choice for a column name.
Why make the year number a VARCHAR anyway?
David Portas
SQL Server MVP
--|||CORRECTION:
SELECT
'ALTER TABLE '+QUOTENAME(table_schema)+'.'+QUOTENAME(table_name)+
' ADD [year_num] VARCHAR(10) NOT NULL'+
' CONSTRAINT [df_'+table_name+'_year_num] DEFAULT (''1999'')'
FROM information_schema.tables ;
David Portas
SQL Server MVP
--sql
Tuesday, March 27, 2012
cursor or while loop?
i have 160,000 rows in a table. need to send out an email to somebody
for each row.
currently using a cursor to loop through the rows and calling COM email
component to send the emails
ran low on resources after about 100,000 records
would it be better to do something like this?
DECLARE @.Rowcount int
SELECT @.RowCount=COUNT(*) from table
WHILE @.RowCount > 0
BEGIN
SELECT TOP 1 @.somevar=somevar FROM table
SET @.RowCount = @.@.ROWCOUNT
IF @.Rowcount > 0
BEGIN
send the email
delete the record
END
END
this would only grab one record at a time. any recommendations?
TIA
NeilPass the result set to the front end and do not try to do this in the
database.|||Check out http://www.sqldev.net there is a xp_smtp_sendmail which you can
use to send your mail.
You will need to use a cursor still because there isn't anything that takes
a set.
I'd create a temporary table or table variable of the rows you want to email
first, then send the emails and join back removing the rows; you might want
recoverability in which case use a permenent table or something similar -
you don't want to lose the position if the server goes down.
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials
<neilmcguigan@.gmail.com> wrote in message
news:1131321608.259481.84490@.g49g2000cwa.googlegroups.com...
> hello,
> i have 160,000 rows in a table. need to send out an email to somebody
> for each row.
> currently using a cursor to loop through the rows and calling COM email
> component to send the emails
> ran low on resources after about 100,000 records
> would it be better to do something like this?
> DECLARE @.Rowcount int
> SELECT @.RowCount=COUNT(*) from table
> WHILE @.RowCount > 0
> BEGIN
> SELECT TOP 1 @.somevar=somevar FROM table
> SET @.RowCount = @.@.ROWCOUNT
> IF @.Rowcount > 0
> BEGIN
> send the email
> delete the record
> END
> END
> this would only grab one record at a time. any recommendations?
> TIA
> Neil
>|||That just won't scale.
The number of round trips 160,000 would be even slower.
This is one of many examples where keeping it inside the SQL Server engine
scales better and is more maintable (you don't have to code using two
different langauges and worry about a front end app).
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials
"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1131322861.083235.253060@.g43g2000cwa.googlegroups.com...
> Pass the result set to the front end and do not try to do this in the
> database.
>|||I really had a lot of reliability problems with sql server mail.
I just don't trust mapi based mail anymore.
xp_smtp_sendmail is dead reliable. I pump huge amounts through it everyday.
What are we going to do with Yukon?
Tony, do you know if xp's written for 2000 will work with 2005 or is the
native mail OK in 2005?
Paul
"Tony Rogerson" <tonyrogerson@.sqlserverfaq.com> wrote in message
news:ekRlvE34FHA.2548@.TK2MSFTNGP10.phx.gbl...
> Check out http://www.sqldev.net there is a xp_smtp_sendmail which you can
> use to send your mail.
> You will need to use a cursor still because there isn't anything that
> takes a set.
> I'd create a temporary table or table variable of the rows you want to
> email first, then send the emails and join back removing the rows; you
> might want recoverability in which case use a permenent table or something
> similar - you don't want to lose the position if the server goes down.
> --
> Tony Rogerson
> SQL Server MVP
> http://sqlserverfaq.com - free video tutorials
>
> <neilmcguigan@.gmail.com> wrote in message
> news:1131321608.259481.84490@.g49g2000cwa.googlegroups.com...
>|||Hi Paul,
Believe me - they got the message with MAPI mail!
Its been rewritten (again), but this time properly - MAPI is only there for
backward compatibility, there is a new SMTP mail built into SQL Server 2005
and its highly scalable too (at last!).
I will be glad to see the back of Outlook 2000 and SQL Server.
Tony.
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials
"Paul Cahill" <xyzpaul.xyzcahill@.dsl.pipex.com> wrote in message
news:OEEASy34FHA.1140@.tk2msftngp13.phx.gbl...
>I really had a lot of reliability problems with sql server mail.
> I just don't trust mapi based mail anymore.
> xp_smtp_sendmail is dead reliable. I pump huge amounts through it
> everyday.
> What are we going to do with Yukon?
> Tony, do you know if xp's written for 2000 will work with 2005 or is the
> native mail OK in 2005?
> Paul
>
> "Tony Rogerson" <tonyrogerson@.sqlserverfaq.com> wrote in message
> news:ekRlvE34FHA.2548@.TK2MSFTNGP10.phx.gbl...
>|||Additional...
You've really got to get your head round what the SQL Server product is now,
its not just a RDBMS its a whole host of things that we can take advantage
of when building applications, be they simple or complex.
You don't have to go off to DB2 etc... in order to build a dimensional
model, you can use Analysis Services which is part of the SQL Server product
set and has been since 2000.
You don't have to go off and buy another text search package, you can use
Full-Text indexing which is built into the product as well.
Please (oh please), bring your knowledge up-to-date; you are so far behind
its embarrasing.
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials
"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1131322861.083235.253060@.g43g2000cwa.googlegroups.com...
> Pass the result set to the front end and do not try to do this in the
> database.
>|||I'm going to have to kindof disagree with you on this one. Making a
round-trip on each result would be a horrendous solution; however,
returing a full batch 160,000 records to the client wouldn't be bad at
all (even if the client were the SQL Server machine.). I consider my
databases to be dynamic entities whose purpose is efficient storage,
retrieval and manipulation of data. I wouldn't dream of calling a COM
component from SQL Server; even the idea of embedding .NET assemblies
in 2005 scares me a bit.
The two solutions I would consider using would be embedded an ActiveX
script in a SQL Server Agent job step. I prefer Python, however,
VBScript and JScript are readily available for use. Or you can easily
throw together a quick .NET console app.
EXAMPLE (Compile using: csc /t:exe SendEMails.cs):
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Mail;
class SendEmails
{
static void Main(string[] args)
{
SqlDataAdapter da = new SqlDataAdapter(@."
SELECT EmailAddress
FROM TableName
", "server=.;database=MyDatabase;integrated security=sspi;");
DataTable dt = new DataTable();
da.Fill(dt);
SmtpMail.SmtpServer =
"smtp.domain.com";
foreach (DataRow dr in dt.Rows)
SmtpMail.Send("from@.domain.com", dr["EmailAddress"].ToString(),
"Subject", "MessageText");
}
}
-Alan|||Thanks Tony that's good news.
Now I've only got to remember how those DTS tasks I wrote last year work :)
Paul
"Tony Rogerson" <tonyrogerson@.sqlserverfaq.com> wrote in message
news:O8r7xG44FHA.2888@.tk2msftngp13.phx.gbl...
> Hi Paul,
> Believe me - they got the message with MAPI mail!
> Its been rewritten (again), but this time properly - MAPI is only there
> for backward compatibility, there is a new SMTP mail built into SQL Server
> 2005 and its highly scalable too (at last!).
> I will be glad to see the back of Outlook 2000 and SQL Server.
> Tony.
> --
> Tony Rogerson
> SQL Server MVP
> http://sqlserverfaq.com - free video tutorials
>
> "Paul Cahill" <xyzpaul.xyzcahill@.dsl.pipex.com> wrote in message
> news:OEEASy34FHA.1140@.tk2msftngp13.phx.gbl...
>|||thanks for all the info guys.
i need something that can run continuously, reliably, minimal resouce
use
thinking i might go to an external program, write a .net service
perhaps.
maybe grab a couple hundred records at a time, process them, update.
i liked the all sql model as it didn't seem to use too many resources.
but i like the error handing in .net better.
Cursor or While Loop or neither?
I am looking for a way to pick specific records from a view I have
created. The data from my view looks like this:
machineid serverdate kioskdate kiosktime
ITG70000011 2004-09-30 01:59:52.000 2004-09-28 00:00:00.000 1900-01-01
02:02:28.000
ITG70000011 2004-09-30 01:59:51.000 2004-09-28 00:00:00.000 1900-01-01
02:02:24.000
ITG70000011 2004-09-30 01:59:51.000 2004-09-28 00:00:00.000 1900-01-01
02:02:24.000
ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
02:02:01.000
ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
02:02:23.000
ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
02:02:23.000
ITG70000009 2004-09-30 01:59:49.000 2004-09-28 00:00:00.000 1900-01-01
02:02:00.000
ITG70000009 2004-09-30 01:59:48.000 2004-09-27 00:00:00.000 1900-01-01
02:02:29.000
ITG70000009 2004-09-30 01:59:48.000 2004-09-27 00:00:00.000 1900-01-01
02:02:30.000
ITG70000008 2004-09-30 01:59:47.000 2004-09-27 00:00:00.000 1900-01-01
02:02:29.000
ITG70000008 2004-09-30 01:59:47.000 2004-09-27 00:00:00.000 1900-01-01
02:02:29.000
ITG70000008 2004-09-30 01:59:46.000 2004-09-27 00:00:00.000 1900-01-01
02:02:28.000
I would like to perform a select which displays every distinct
machineid ordered by serverdate, so the above resultset would look
like this:
ITG70000011 2004-09-30 01:59:52.000 2004-09-28 00:00:00.000 1900-01-01
02:02:28.000
ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
02:02:01.000
ITG70000009 2004-09-30 01:59:49.000 2004-09-28 00:00:00.000 1900-01-01
02:02:00.000
ITG70000008 2004-09-30 01:59:47.000 2004-09-27 00:00:00.000 1900-01-01
02:02:29.000
I have tried using select distinct machine, serverdate, kioskdate from
V_MyView however this still returns every single result. Do I need to
use a Cursor or a while..loop?
Thanks
Scott
This is just a guess, but perhaps you are loooking for something like this?
SELECT machineid, MAX(serverdate) as serverdate,
MAX(kioskdate) AS kioskdate, MAX(kiosktime) AS kiosktime
FROM V_MyView
By the way, why do you store kiosk 'date' and 'time' in two different
columns?
Keith
"scott" <quackhandle1975@.yahoo.co.uk> wrote in message
news:3af9ea3d.0409300540.37b38151@.posting.google.c om...
> Hi,
> I am looking for a way to pick specific records from a view I have
> created. The data from my view looks like this:
> machineid serverdate kioskdate kiosktime
> ITG70000011 2004-09-30 01:59:52.000 2004-09-28 00:00:00.000 1900-01-01
> 02:02:28.000
> ITG70000011 2004-09-30 01:59:51.000 2004-09-28 00:00:00.000 1900-01-01
> 02:02:24.000
> ITG70000011 2004-09-30 01:59:51.000 2004-09-28 00:00:00.000 1900-01-01
> 02:02:24.000
> ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
> 02:02:01.000
> ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
> 02:02:23.000
> ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
> 02:02:23.000
> ITG70000009 2004-09-30 01:59:49.000 2004-09-28 00:00:00.000 1900-01-01
> 02:02:00.000
> ITG70000009 2004-09-30 01:59:48.000 2004-09-27 00:00:00.000 1900-01-01
> 02:02:29.000
> ITG70000009 2004-09-30 01:59:48.000 2004-09-27 00:00:00.000 1900-01-01
> 02:02:30.000
> ITG70000008 2004-09-30 01:59:47.000 2004-09-27 00:00:00.000 1900-01-01
> 02:02:29.000
> ITG70000008 2004-09-30 01:59:47.000 2004-09-27 00:00:00.000 1900-01-01
> 02:02:29.000
> ITG70000008 2004-09-30 01:59:46.000 2004-09-27 00:00:00.000 1900-01-01
> 02:02:28.000
> I would like to perform a select which displays every distinct
> machineid ordered by serverdate, so the above resultset would look
> like this:
> ITG70000011 2004-09-30 01:59:52.000 2004-09-28 00:00:00.000 1900-01-01
> 02:02:28.000
> ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
> 02:02:01.000
> ITG70000009 2004-09-30 01:59:49.000 2004-09-28 00:00:00.000 1900-01-01
> 02:02:00.000
> ITG70000008 2004-09-30 01:59:47.000 2004-09-27 00:00:00.000 1900-01-01
> 02:02:29.000
> I have tried using select distinct machine, serverdate, kioskdate from
> V_MyView however this still returns every single result. Do I need to
> use a Cursor or a while..loop?
> Thanks
>
> Scott
|||I think he will also need a GROUP BY clause.
SELECT machineid, MAX(serverdate) as serverdate,
MAX(kioskdate) AS kioskdate, MAX(kiosktime) AS kiosktime
FROM V_MyView
GROUP BY machineid
"Keith Kratochvil" wrote:
> This is just a guess, but perhaps you are loooking for something like this?
> SELECT machineid, MAX(serverdate) as serverdate,
> MAX(kioskdate) AS kioskdate, MAX(kiosktime) AS kiosktime
> FROM V_MyView
> By the way, why do you store kiosk 'date' and 'time' in two different
> columns?
> --
> Keith
>
> "scott" <quackhandle1975@.yahoo.co.uk> wrote in message
> news:3af9ea3d.0409300540.37b38151@.posting.google.c om...
>
|||Yep, missed that one. I hit Send too quickly.
Keith
"mthomason" <mthomason@.discussions.microsoft.com> wrote in message
news:A25A8079-9D5E-4DAB-A56B-E4BA779DF386@.microsoft.com...[vbcol=seagreen]
> I think he will also need a GROUP BY clause.
> SELECT machineid, MAX(serverdate) as serverdate,
> MAX(kioskdate) AS kioskdate, MAX(kiosktime) AS kiosktime
> FROM V_MyView
> GROUP BY machineid
> "Keith Kratochvil" wrote:
this?[vbcol=seagreen]
|||On 30 Sep 2004 06:40:27 -0700, scott wrote:
>Hi,
>I am looking for a way to pick specific records from a view I have
>created. The data from my view looks like this:
(snip)
>I would like to perform a select which displays every distinct
>machineid ordered by serverdate, so the above resultset would look
>like this:
(snip)
Hi Scott,
Looking at your expected results, it looks as if you want to find the row
with the highest serverdate for each machineid, then display all columns
of that row. Correct?
>I have tried using select distinct machine, serverdate, kioskdate from
>V_MyView however this still returns every single result. Do I need to
>use a Cursor or a while..loop?
Neither. Try the following SQL:
SELECT machineid, serverdate, kioskdate, kiosktime
FROM YourView AS a
WHERE NOT EXISTS
(SELECT *
FROM YourView AS b
WHERE b.machineid = a.machineid
AND b.serverdate > a.serverdate)
Or try the following alternative:
SELECT a.machineid, a.serverdate, a.kioskdate, a.kiosktime
FROM YourView AS a
INNER JOIN (SELECT machineid, MAX(serverdate)
FROM YourView
GROUP BY machineid) AS b(machineid, maxserverdate)
ON a.machineid = b.machineid
AND a.serverdate = b.maxserverdate
(Both queries are untested)
Best, Hugo
(Remove _NO_ and _SPAM_ to get my e-mail address)
|||Thanks for all your replies, Keith is the winner, can't beleive I
forgot about using "max"!
Rgds,
Scott
"Keith Kratochvil" <sqlguy.back2u@.comcast.net> wrote in message news:<#LLMqlwpEHA.592@.TK2MSFTNGP11.phx.gbl>...[vbcol=seagreen]
> Yep, missed that one. I hit Send too quickly.
> --
> Keith
>
> "mthomason" <mthomason@.discussions.microsoft.com> wrote in message
> news:A25A8079-9D5E-4DAB-A56B-E4BA779DF386@.microsoft.com...
> this?
sql
Cursor or While Loop or neither?
I am looking for a way to pick specific records from a view I have
created. The data from my view looks like this:
machineid serverdate kioskdate kiosktime
ITG70000011 2004-09-30 01:59:52.000 2004-09-28 00:00:00.000 1900-01-01
02:02:28.000
ITG70000011 2004-09-30 01:59:51.000 2004-09-28 00:00:00.000 1900-01-01
02:02:24.000
ITG70000011 2004-09-30 01:59:51.000 2004-09-28 00:00:00.000 1900-01-01
02:02:24.000
ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
02:02:01.000
ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
02:02:23.000
ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
02:02:23.000
ITG70000009 2004-09-30 01:59:49.000 2004-09-28 00:00:00.000 1900-01-01
02:02:00.000
ITG70000009 2004-09-30 01:59:48.000 2004-09-27 00:00:00.000 1900-01-01
02:02:29.000
ITG70000009 2004-09-30 01:59:48.000 2004-09-27 00:00:00.000 1900-01-01
02:02:30.000
ITG70000008 2004-09-30 01:59:47.000 2004-09-27 00:00:00.000 1900-01-01
02:02:29.000
ITG70000008 2004-09-30 01:59:47.000 2004-09-27 00:00:00.000 1900-01-01
02:02:29.000
ITG70000008 2004-09-30 01:59:46.000 2004-09-27 00:00:00.000 1900-01-01
02:02:28.000
I would like to perform a select which displays every distinct
machineid ordered by serverdate, so the above resultset would look
like this:
ITG70000011 2004-09-30 01:59:52.000 2004-09-28 00:00:00.000 1900-01-01
02:02:28.000
ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
02:02:01.000
ITG70000009 2004-09-30 01:59:49.000 2004-09-28 00:00:00.000 1900-01-01
02:02:00.000
ITG70000008 2004-09-30 01:59:47.000 2004-09-27 00:00:00.000 1900-01-01
02:02:29.000
I have tried using select distinct machine, serverdate, kioskdate from
V_MyView however this still returns every single result. Do I need to
use a Cursor or a while..loop?
Thanks
ScottThis is just a guess, but perhaps you are loooking for something like this?
SELECT machineid, MAX(serverdate) as serverdate,
MAX(kioskdate) AS kioskdate, MAX(kiosktime) AS kiosktime
FROM V_MyView
By the way, why do you store kiosk 'date' and 'time' in two different
columns?
--
Keith
"scott" <quackhandle1975@.yahoo.co.uk> wrote in message
news:3af9ea3d.0409300540.37b38151@.posting.google.com...
> Hi,
> I am looking for a way to pick specific records from a view I have
> created. The data from my view looks like this:
> machineid serverdate kioskdate kiosktime
> ITG70000011 2004-09-30 01:59:52.000 2004-09-28 00:00:00.000 1900-01-01
> 02:02:28.000
> ITG70000011 2004-09-30 01:59:51.000 2004-09-28 00:00:00.000 1900-01-01
> 02:02:24.000
> ITG70000011 2004-09-30 01:59:51.000 2004-09-28 00:00:00.000 1900-01-01
> 02:02:24.000
> ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
> 02:02:01.000
> ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
> 02:02:23.000
> ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
> 02:02:23.000
> ITG70000009 2004-09-30 01:59:49.000 2004-09-28 00:00:00.000 1900-01-01
> 02:02:00.000
> ITG70000009 2004-09-30 01:59:48.000 2004-09-27 00:00:00.000 1900-01-01
> 02:02:29.000
> ITG70000009 2004-09-30 01:59:48.000 2004-09-27 00:00:00.000 1900-01-01
> 02:02:30.000
> ITG70000008 2004-09-30 01:59:47.000 2004-09-27 00:00:00.000 1900-01-01
> 02:02:29.000
> ITG70000008 2004-09-30 01:59:47.000 2004-09-27 00:00:00.000 1900-01-01
> 02:02:29.000
> ITG70000008 2004-09-30 01:59:46.000 2004-09-27 00:00:00.000 1900-01-01
> 02:02:28.000
> I would like to perform a select which displays every distinct
> machineid ordered by serverdate, so the above resultset would look
> like this:
> ITG70000011 2004-09-30 01:59:52.000 2004-09-28 00:00:00.000 1900-01-01
> 02:02:28.000
> ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
> 02:02:01.000
> ITG70000009 2004-09-30 01:59:49.000 2004-09-28 00:00:00.000 1900-01-01
> 02:02:00.000
> ITG70000008 2004-09-30 01:59:47.000 2004-09-27 00:00:00.000 1900-01-01
> 02:02:29.000
> I have tried using select distinct machine, serverdate, kioskdate from
> V_MyView however this still returns every single result. Do I need to
> use a Cursor or a while..loop?
> Thanks
>
> Scott|||I think he will also need a GROUP BY clause.
SELECT machineid, MAX(serverdate) as serverdate,
MAX(kioskdate) AS kioskdate, MAX(kiosktime) AS kiosktime
FROM V_MyView
GROUP BY machineid
"Keith Kratochvil" wrote:
> This is just a guess, but perhaps you are loooking for something like this?
> SELECT machineid, MAX(serverdate) as serverdate,
> MAX(kioskdate) AS kioskdate, MAX(kiosktime) AS kiosktime
> FROM V_MyView
> By the way, why do you store kiosk 'date' and 'time' in two different
> columns?
> --
> Keith
>
> "scott" <quackhandle1975@.yahoo.co.uk> wrote in message
> news:3af9ea3d.0409300540.37b38151@.posting.google.com...
> > Hi,
> >
> > I am looking for a way to pick specific records from a view I have
> > created. The data from my view looks like this:
> >
> > machineid serverdate kioskdate kiosktime
> >
> > ITG70000011 2004-09-30 01:59:52.000 2004-09-28 00:00:00.000 1900-01-01
> > 02:02:28.000
> > ITG70000011 2004-09-30 01:59:51.000 2004-09-28 00:00:00.000 1900-01-01
> > 02:02:24.000
> > ITG70000011 2004-09-30 01:59:51.000 2004-09-28 00:00:00.000 1900-01-01
> > 02:02:24.000
> > ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
> > 02:02:01.000
> > ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
> > 02:02:23.000
> > ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
> > 02:02:23.000
> > ITG70000009 2004-09-30 01:59:49.000 2004-09-28 00:00:00.000 1900-01-01
> > 02:02:00.000
> > ITG70000009 2004-09-30 01:59:48.000 2004-09-27 00:00:00.000 1900-01-01
> > 02:02:29.000
> > ITG70000009 2004-09-30 01:59:48.000 2004-09-27 00:00:00.000 1900-01-01
> > 02:02:30.000
> > ITG70000008 2004-09-30 01:59:47.000 2004-09-27 00:00:00.000 1900-01-01
> > 02:02:29.000
> > ITG70000008 2004-09-30 01:59:47.000 2004-09-27 00:00:00.000 1900-01-01
> > 02:02:29.000
> > ITG70000008 2004-09-30 01:59:46.000 2004-09-27 00:00:00.000 1900-01-01
> > 02:02:28.000
> >
> > I would like to perform a select which displays every distinct
> > machineid ordered by serverdate, so the above resultset would look
> > like this:
> >
> > ITG70000011 2004-09-30 01:59:52.000 2004-09-28 00:00:00.000 1900-01-01
> > 02:02:28.000
> > ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
> > 02:02:01.000
> > ITG70000009 2004-09-30 01:59:49.000 2004-09-28 00:00:00.000 1900-01-01
> > 02:02:00.000
> > ITG70000008 2004-09-30 01:59:47.000 2004-09-27 00:00:00.000 1900-01-01
> > 02:02:29.000
> >
> > I have tried using select distinct machine, serverdate, kioskdate from
> > V_MyView however this still returns every single result. Do I need to
> > use a Cursor or a while..loop?
> >
> > Thanks
> >
> >
> >
> > Scott
>|||Yep, missed that one. I hit Send too quickly.
--
Keith
"mthomason" <mthomason@.discussions.microsoft.com> wrote in message
news:A25A8079-9D5E-4DAB-A56B-E4BA779DF386@.microsoft.com...
> I think he will also need a GROUP BY clause.
> SELECT machineid, MAX(serverdate) as serverdate,
> MAX(kioskdate) AS kioskdate, MAX(kiosktime) AS kiosktime
> FROM V_MyView
> GROUP BY machineid
> "Keith Kratochvil" wrote:
> > This is just a guess, but perhaps you are loooking for something like
this?
> >
> > SELECT machineid, MAX(serverdate) as serverdate,
> > MAX(kioskdate) AS kioskdate, MAX(kiosktime) AS kiosktime
> > FROM V_MyView
> >
> > By the way, why do you store kiosk 'date' and 'time' in two different
> > columns?
> >
> > --
> > Keith
> >
> >
> > "scott" <quackhandle1975@.yahoo.co.uk> wrote in message
> > news:3af9ea3d.0409300540.37b38151@.posting.google.com...
> > > Hi,
> > >
> > > I am looking for a way to pick specific records from a view I have
> > > created. The data from my view looks like this:
> > >
> > > machineid serverdate kioskdate kiosktime
> > >
> > > ITG70000011 2004-09-30 01:59:52.000 2004-09-28 00:00:00.000 1900-01-01
> > > 02:02:28.000
> > > ITG70000011 2004-09-30 01:59:51.000 2004-09-28 00:00:00.000 1900-01-01
> > > 02:02:24.000
> > > ITG70000011 2004-09-30 01:59:51.000 2004-09-28 00:00:00.000 1900-01-01
> > > 02:02:24.000
> > > ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
> > > 02:02:01.000
> > > ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
> > > 02:02:23.000
> > > ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
> > > 02:02:23.000
> > > ITG70000009 2004-09-30 01:59:49.000 2004-09-28 00:00:00.000 1900-01-01
> > > 02:02:00.000
> > > ITG70000009 2004-09-30 01:59:48.000 2004-09-27 00:00:00.000 1900-01-01
> > > 02:02:29.000
> > > ITG70000009 2004-09-30 01:59:48.000 2004-09-27 00:00:00.000 1900-01-01
> > > 02:02:30.000
> > > ITG70000008 2004-09-30 01:59:47.000 2004-09-27 00:00:00.000 1900-01-01
> > > 02:02:29.000
> > > ITG70000008 2004-09-30 01:59:47.000 2004-09-27 00:00:00.000 1900-01-01
> > > 02:02:29.000
> > > ITG70000008 2004-09-30 01:59:46.000 2004-09-27 00:00:00.000 1900-01-01
> > > 02:02:28.000
> > >
> > > I would like to perform a select which displays every distinct
> > > machineid ordered by serverdate, so the above resultset would look
> > > like this:
> > >
> > > ITG70000011 2004-09-30 01:59:52.000 2004-09-28 00:00:00.000 1900-01-01
> > > 02:02:28.000
> > > ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
> > > 02:02:01.000
> > > ITG70000009 2004-09-30 01:59:49.000 2004-09-28 00:00:00.000 1900-01-01
> > > 02:02:00.000
> > > ITG70000008 2004-09-30 01:59:47.000 2004-09-27 00:00:00.000 1900-01-01
> > > 02:02:29.000
> > >
> > > I have tried using select distinct machine, serverdate, kioskdate from
> > > V_MyView however this still returns every single result. Do I need to
> > > use a Cursor or a while..loop?
> > >
> > > Thanks
> > >
> > >
> > >
> > > Scott
> >
> >|||On 30 Sep 2004 06:40:27 -0700, scott wrote:
>Hi,
>I am looking for a way to pick specific records from a view I have
>created. The data from my view looks like this:
(snip)
>I would like to perform a select which displays every distinct
>machineid ordered by serverdate, so the above resultset would look
>like this:
(snip)
Hi Scott,
Looking at your expected results, it looks as if you want to find the row
with the highest serverdate for each machineid, then display all columns
of that row. Correct?
>I have tried using select distinct machine, serverdate, kioskdate from
>V_MyView however this still returns every single result. Do I need to
>use a Cursor or a while..loop?
Neither. Try the following SQL:
SELECT machineid, serverdate, kioskdate, kiosktime
FROM YourView AS a
WHERE NOT EXISTS
(SELECT *
FROM YourView AS b
WHERE b.machineid = a.machineid
AND b.serverdate > a.serverdate)
Or try the following alternative:
SELECT a.machineid, a.serverdate, a.kioskdate, a.kiosktime
FROM YourView AS a
INNER JOIN (SELECT machineid, MAX(serverdate)
FROM YourView
GROUP BY machineid) AS b(machineid, maxserverdate)
ON a.machineid = b.machineid
AND a.serverdate = b.maxserverdate
(Both queries are untested)
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||Thanks for all your replies, Keith is the winner, can't beleive I
forgot about using "max"!
Rgds,
Scott
"Keith Kratochvil" <sqlguy.back2u@.comcast.net> wrote in message news:<#LLMqlwpEHA.592@.TK2MSFTNGP11.phx.gbl>...
> Yep, missed that one. I hit Send too quickly.
> --
> Keith
>
> "mthomason" <mthomason@.discussions.microsoft.com> wrote in message
> news:A25A8079-9D5E-4DAB-A56B-E4BA779DF386@.microsoft.com...
> > I think he will also need a GROUP BY clause.
> >
> > SELECT machineid, MAX(serverdate) as serverdate,
> > MAX(kioskdate) AS kioskdate, MAX(kiosktime) AS kiosktime
> > FROM V_MyView
> > GROUP BY machineid
> >
> > "Keith Kratochvil" wrote:
> >
> > > This is just a guess, but perhaps you are loooking for something like
> this?
> > >
> > > SELECT machineid, MAX(serverdate) as serverdate,
> > > MAX(kioskdate) AS kioskdate, MAX(kiosktime) AS kiosktime
> > > FROM V_MyView
> > >
> > > By the way, why do you store kiosk 'date' and 'time' in two different
> > > columns?
> > >
> > > --
> > > Keith
> > >
> > >
> > > "scott" <quackhandle1975@.yahoo.co.uk> wrote in message
> > > news:3af9ea3d.0409300540.37b38151@.posting.google.com...
> > > > Hi,
> > > >
> > > > I am looking for a way to pick specific records from a view I have
> > > > created. The data from my view looks like this:
> > > >
> > > > machineid serverdate kioskdate kiosktime
> > > >
> > > > ITG70000011 2004-09-30 01:59:52.000 2004-09-28 00:00:00.000 1900-01-01
> > > > 02:02:28.000
> > > > ITG70000011 2004-09-30 01:59:51.000 2004-09-28 00:00:00.000 1900-01-01
> > > > 02:02:24.000
> > > > ITG70000011 2004-09-30 01:59:51.000 2004-09-28 00:00:00.000 1900-01-01
> > > > 02:02:24.000
> > > > ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
> > > > 02:02:01.000
> > > > ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
> > > > 02:02:23.000
> > > > ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
> > > > 02:02:23.000
> > > > ITG70000009 2004-09-30 01:59:49.000 2004-09-28 00:00:00.000 1900-01-01
> > > > 02:02:00.000
> > > > ITG70000009 2004-09-30 01:59:48.000 2004-09-27 00:00:00.000 1900-01-01
> > > > 02:02:29.000
> > > > ITG70000009 2004-09-30 01:59:48.000 2004-09-27 00:00:00.000 1900-01-01
> > > > 02:02:30.000
> > > > ITG70000008 2004-09-30 01:59:47.000 2004-09-27 00:00:00.000 1900-01-01
> > > > 02:02:29.000
> > > > ITG70000008 2004-09-30 01:59:47.000 2004-09-27 00:00:00.000 1900-01-01
> > > > 02:02:29.000
> > > > ITG70000008 2004-09-30 01:59:46.000 2004-09-27 00:00:00.000 1900-01-01
> > > > 02:02:28.000
> > > >
> > > > I would like to perform a select which displays every distinct
> > > > machineid ordered by serverdate, so the above resultset would look
> > > > like this:
> > > >
> > > > ITG70000011 2004-09-30 01:59:52.000 2004-09-28 00:00:00.000 1900-01-01
> > > > 02:02:28.000
> > > > ITG70000010 2004-09-30 01:59:50.000 2004-09-28 00:00:00.000 1900-01-01
> > > > 02:02:01.000
> > > > ITG70000009 2004-09-30 01:59:49.000 2004-09-28 00:00:00.000 1900-01-01
> > > > 02:02:00.000
> > > > ITG70000008 2004-09-30 01:59:47.000 2004-09-27 00:00:00.000 1900-01-01
> > > > 02:02:29.000
> > > >
> > > > I have tried using select distinct machine, serverdate, kioskdate from
> > > > V_MyView however this still returns every single result. Do I need to
> > > > use a Cursor or a while..loop?
> > > >
> > > > Thanks
> > > >
> > > >
> > > >
> > > > Scott
> > >
> > >
Cursor Loop Problem
Hey everyone,
I'm running a cursor to concatinate text into a field. I have a work order table with workOrderID as the unique identifyer. I have a comments table that has a foreign key to workOrderID. There is a one-to-many relationship between the tables as a work order can have multiple comments.
I've got a field in the work order table that is supposed to store all the comments for that work order concatenated together. This is the script I am using:
DECLARE @.Comments varchar(8000);
DECLARE @.WorkOrderID VARCHAR(9); -- unique identifier
DECLARE C1 CURSOR
FOR
SELECT c.Comment , w.JobOrder
FROM tblWorkOrderComments AS c
INNER JOIN tblCallIns AS w
ON c.WorkOrder = w.JobOrder
WHERE w.Comments IS NULL;
OPEN C1;
FETCH NEXT FROM C1 INTO @.Comments ,@.WorkOrderID ; -- include the unique identifier into Fetch
WHILE (@.@.FETCH_STATUS <> -1)
BEGIN
IF (@.@.FETCH_STATUS <> -2)
BEGIN
UPDATE tblCallIns
SET tblCallIns.Comments = ISNULL(tblCallIns.Comments,'') + CHAR(13) + ISNULL(@.Comments,'') -- concatenate comments
WHERE JobOrder = @.WorkOrderID -- filter updated records
END;
FETCH NEXT FROM C1 INTO @.Comments ,@.WorkOrderID ;
END;
CLOSE C1;
DEALLOCATE C1;
It's only pulling the first comment into the comments field and not grabbing any additional comments for the work order.
Can anyone see what's wrong with my code?
Thanks,
Lee
After the UPDATE the w.comments referenced in the cursor is no longer null.
|||Lee,
I think you want to specify FORWARD_ONLY, STATIC, and KEYSET in your CURSOR declaration.
Otherwise the CURSOR is DYNAMIC, and working in light of your UPDATE actions.
http://msdn2.microsoft.com/en-us/library/ms180169.aspx
Hope that helps,
Dan
|||hi try this..DECLARE @.tblWorkOrderComments TABLE (WorkOrder INT, Comment VARCHAR(800))
DECLARE @.tblCallIns TABLE (JobOrder INT, Comments VARCHAR(800))
INSERT INTO @.tblWorkOrderComments VALUES (1, 'the')
INSERT INTO @.tblWorkOrderComments VALUES (1, 'quick')
INSERT INTO @.tblWorkOrderComments VALUES (1, 'brown')
INSERT INTO @.tblWorkOrderComments VALUES (2, 'fox')
INSERT INTO @.tblWorkOrderComments VALUES (2, 'jumps')
INSERT INTO @.tblCallIns VALUES (1, NULL)
INSERT INTO @.tblCallIns VALUES (2, NULL)
INSERT INTO @.tblCallIns VALUES (3, NULL)
INSERT INTO @.tblCallIns VALUES (4, NULL)
DECLARE @.Comments varchar(8000);
DECLARE @.WorkOrderID VARCHAR(9); -- unique identifier
DECLARE C1 CURSOR FOR
SELECT DISTINCT w.JobOrder -- get only the joborder with comments
FROM @.tblWorkOrderComments AS c
INNER JOIN @.tblCallIns AS w
ON c.WorkOrder = w.JobOrder
WHERE w.Comments IS NULL;
OPEN C1;
FETCH NEXT FROM C1 INTO @.WorkOrderID ; -- include the unique identifier into Fetch
WHILE (@.@.FETCH_STATUS = 0)
BEGIN
--IF (@.@.FETCH_STATUS <> -2)
--BEGIN
SET @.Comments = ''
SELECT @.Comments = @.Comments + CHAR(13) + ISNULL(Comment,'') -- this will concatenate all the comments per workorder
FROM @.tblWorkOrderComments
WHERE WorkOrder = @.WorkOrderID
ORDER BY
WorkOrder
UPDATE @.tblCallIns
SET Comments = @.Comments -- concatenate comments
WHERE JobOrder = @.WorkOrderID -- filter updated records
--END;
FETCH NEXT FROM C1 INTO @.WorkOrderID ;
END;
CLOSE C1;
DEALLOCATE C1;
SELECT * FROM @.tblWorkOrderComments
SELECT * FROM @.tblCallInssql
Cursor loop is broken
from Table1. Each record in the cursor is inserted into Table2.
Insert trigger on Table2 is inserting the record into Table3 (in
another DB).
In the insert trigger on Table3, a series on checks are done on the
inserted record and in case of an error, an email is sent and the
trigger returns.
This break the cursorloop in SP1 and the rest of the records in the
cursor is not treated.
How do I make sure that all records are treated?
This is the flow:
-- SP1 --
DECLARE csrListe CURSOR FOR SELECT felt1 FROM Table1
OPEN csrListe
-- The first record is treated here...
:
-- Treat the rest
WHILE @.@.FETCH_STATUS = 0 BEGIN
FETCH NEXT FROM csrListe INTO @.feltet
IF @.@.FETCH_STATUS = 0 BEGIN
blah-blah-blah
INSERT INTO Table2 (Ordrenr, Status, Dato, Resultat) VALUES
(@.Ordrenr, @.Status, @.Dato, @.Result)
END
END
CLOSE csrListe
DEALLOCATE csrListe
-- Table2_ITrig --
INSERT INTO db2.dbo.Table3 SELECT * FROM inserted
-- Table3_ITrig --
SET NOCOUNT ON
DECLARE @.STATUS int
DECLARE @.DATOTID smalldatetime
DECLARE @.RESULT int
SELECT @.ORDRENR = (SELECT ORDRENR FROM INSERTED)
SELECT @.STATUS = (SELECT STATUS FROM INSERTED)
SELECT @.DATOTID = (SELECT DATO FROM INSERTED)
SELECT @.RESULT = (SELECT RESULT FROM INSERTED)
SET XACT_ABORT ON
IF NOT @.STATUS IN (1,2,3,4,5,6,9,10) BEGIN
SELECT @.ERR = 'ERROR - unknown status = ' + CAST(@.ORDRENR as char(4))
UPDATE Table3 SET RESULTAT=2 WHERE ORDRENUMMER=@.ORDRENR
EXEC @.rc = master.dbo.xp_smtp_sendmail
@.FROM = N'me@.here.dk',
@.TO = N'you@.here.dk',
@.priority = N'HIGH',
@.subject = N'Status error',
@.message = N'Status error',
@.type = N'text/plain',
@.server = 'smtp.here.dk'
RETURN
END
The mail is send so it must be the final RETURN that is causing the
trouble.sblar wrote:
> In a stored procedure (SP1) I am looping through a cursor with records
> from Table1. Each record in the cursor is inserted into Table2.
> Insert trigger on Table2 is inserting the record into Table3 (in
> another DB).
> In the insert trigger on Table3, a series on checks are done on the
> inserted record and in case of an error, an email is sent and the
> trigger returns.
> This break the cursorloop in SP1 and the rest of the records in the
> cursor is not treated.
> How do I make sure that all records are treated?
> This is the flow:
> -- SP1 --
> DECLARE csrListe CURSOR FOR SELECT felt1 FROM Table1
> OPEN csrListe
> -- The first record is treated here...
> :
> -- Treat the rest
> WHILE @.@.FETCH_STATUS = 0 BEGIN
> FETCH NEXT FROM csrListe INTO @.feltet
> IF @.@.FETCH_STATUS = 0 BEGIN
> blah-blah-blah
> INSERT INTO Table2 (Ordrenr, Status, Dato, Resultat) VALUES
> (@.Ordrenr, @.Status, @.Dato, @.Result)
> END
> END
> CLOSE csrListe
> DEALLOCATE csrListe
> -- Table2_ITrig --
> INSERT INTO db2.dbo.Table3 SELECT * FROM inserted
> -- Table3_ITrig --
> SET NOCOUNT ON
> DECLARE @.STATUS int
> DECLARE @.DATOTID smalldatetime
> DECLARE @.RESULT int
>
> SELECT @.ORDRENR = (SELECT ORDRENR FROM INSERTED)
> SELECT @.STATUS = (SELECT STATUS FROM INSERTED)
> SELECT @.DATOTID = (SELECT DATO FROM INSERTED)
> SELECT @.RESULT = (SELECT RESULT FROM INSERTED)
> SET XACT_ABORT ON
>
> IF NOT @.STATUS IN (1,2,3,4,5,6,9,10) BEGIN
> SELECT @.ERR = 'ERROR - unknown status = ' + CAST(@.ORDRENR as char(4))
> UPDATE Table3 SET RESULTAT=2 WHERE ORDRENUMMER=@.ORDRENR
> EXEC @.rc = master.dbo.xp_smtp_sendmail
> @.FROM = N'me@.here.dk',
> @.TO = N'you@.here.dk',
> @.priority = N'HIGH',
> @.subject = N'Status error',
> @.message = N'Status error',
> @.type = N'text/plain',
> @.server = 'smtp.here.dk'
> RETURN
> END
> The mail is send so it must be the final RETURN that is causing the
> trouble.
Do not use cursors in triggers. Doubly important, do not send email
from a trigger.
See:
http://groups.google.co.uk/group/mi...b273c91159441f2
David Portas
SQL Server MVP
--|||Thanks David, I understand your point about email and will consider
another path, but the problem here doesn't seem to be the email which
is sent ok. The cursor is in the sp not the trigger.
/S=F8ren|||"Sren Larsen" <sblar1@.surfpost.dk> wrote in message
news:1136633487.767264.30440@.g49g2000cwa.googlegroups.com...
Thanks David, I understand your point about email and will consider
another path, but the problem here doesn't seem to be the email which
is sent ok. The cursor is in the sp not the trigger.
/Sren
First, I suggest you get rid of the cursor. Use an INSERT ... SELECT
statement instead:
INSERT INTO Table2 (Ordrenr, Status, Dato, Resultat)
SELECT Ordrenr, Status, Dato, Resultat
FROM ... ?
I expect there was more processing that you left out of your post but I can
only suggest a solution for what you posted.
Secondly, you need to modify your trigger to handle multiple rows properly.
Example:
/* This will FAIL if more than one row is inserted/updated */
SELECT @.ORDRENR = (SELECT ORDRENR FROM INSERTED)
If you don't send emails from the trigger then you won't need to assign the
column values to variables.
David Portas
SQL Server MVP
--|||David Portas (REMOVE_BEFORE_REPLYING_dportas@.acm.org) writes:
> First, I suggest you get rid of the cursor. Use an INSERT ... SELECT
> statement instead:
> INSERT INTO Table2 (Ordrenr, Status, Dato, Resultat)
> SELECT Ordrenr, Status, Dato, Resultat
> FROM ... ?
> I expect there was more processing that you left out of your post but I
> can only suggest a solution for what you posted.
> Secondly, you need to modify your trigger to handle multiple rows
> properly.
> Example:
> /* This will FAIL if more than one row is inserted/updated */
> SELECT @.ORDRENR = (SELECT ORDRENR FROM INSERTED)
> If you don't send emails from the trigger then you won't need to assign
> the column values to variables.
Hey, I've already said all of that! (Except the point of not sending
mail from a trigger.) But I said it in a different newsgroup, as Sren
posted the message independently to two newsgroups. With the result
that I and David waste our time to say the same thing.
Please do not do that again!
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Thanks David.
The cursor is in the sp not the trigger. I understand your point about
email though, and I will consider another path. But, this doesn't seem
to be the problem here as the email is sent.|||Sren Larsen (sblar1_thisisnotme@.surfpost.dk) writes:
> Anyway, thanks for your answers. I'm aware of the problem if my trigger
> receives multiple rows, which it dont cause its only called from my SP
> with the cursor loop. I would however very much like to avoid this way
> of processing but I can't see how if I want to do some processing on
> each row inserted. For example:
> if Status = 1
> set @.result = 2
> if Status = 2
> set @.result = 3
> update sometable set Status = @.Status where number = select number from
> inserted
> Any suggestions?
Without knowledge of the business problem, it's difficult to suggest a
complete solution. But for the particular problem you appear to illustrate
you can use the CASE expression:
UPDATE a
SET result = CASE b.status
WHEN 1 THEN 'OK'
WHEN 2 THEN 'OK with warnings'
WHEN 3 THEN 'Failed'
ELSE 'Complete disaster'
END
FROM a
JOIN b ON a.col = b.col
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||"Erland Sommarskog" <esquel@.sommarskog.se> skrev i en meddelelse
news:Xns9745A1206A4E9Yazorman@.127.0.0.1...
> Without knowledge of the business problem, it's difficult to suggest a
> complete solution. But for the particular problem you appear to illustrate
> you can use the CASE expression:
> UPDATE a
> SET result = CASE b.status
> WHEN 1 THEN 'OK'
> WHEN 2 THEN 'OK with warnings'
> WHEN 3 THEN 'Failed'
> ELSE 'Complete disaster'
> END
> FROM a
> JOIN b ON a.col = b.col
>
Aha - thats neat. Does this mean that inserted are traversed and a.result
would be updated for every row in inserted and can it be done more than once
like this?
UPDATE a
SET result = CASE inserted.status
WHEN 1 THEN 'OK'
WHEN 2 THEN 'OK with warnings'
WHEN 3 THEN 'Failed'
ELSE 'Complete disaster'
END
FROM a
JOIN inserted ON a.col = inserted.col
UPDATE c
SET somefield = CASE inserted.someotherfield
WHEN 1 THEN 11
WHEN 2 THEN 12
WHEN 3 THEN 13
ELSE 0
END
FROM c
JOIN inserted ON c.col = inserted.col
Will this do an update of both a and c based on inserted rows?
/Sren|||I almost forgot; why is the cursorloop broken in the first place? There was
no error in trigger, unless RETURN is considered an error!
/Sren|||Sren Larsen (sblar1_thisisnotme@.surfpost.dk) writes:
> Aha - thats neat. Does this mean that inserted are traversed and
> a.result would be updated for every row in inserted and can it be done
> more than once like this?
> UPDATE a
> SET result = CASE inserted.status
> WHEN 1 THEN 'OK'
> WHEN 2 THEN 'OK with warnings'
> WHEN 3 THEN 'Failed'
> ELSE 'Complete disaster'
> END
> FROM a
> JOIN inserted ON a.col = inserted.col
> UPDATE c
> SET somefield = CASE inserted.someotherfield
> WHEN 1 THEN 11
> WHEN 2 THEN 12
> WHEN 3 THEN 13
> ELSE 0
> END
> FROM c
> JOIN inserted ON c.col = inserted.col
> Will this do an update of both a and c based on inserted rows?
Yes. CASE is extremely powerful when working with set-based operations.
The above is a simplifed form. The more general form is like this:
CASE WHEN somecolumn IN (1, 2, 3) THEN 'This'
WHEN othercolumn = 'A' AND somecolumn = 34 THEN 'That'
WHEN somecolumn < 0 THEN CASE col WHEN 1 THEN 'J' ELSE 'N' END
END
So you can test for more general conditions, and you can nest CASE.
The conditions are always evaluated top-down, and evaluation stops
as soon one matches. If no condition is true, and there is on ELSE,
the value is NULL.
Important to understand is that CASE is an *expression*, and as a
an expression it always return the same data type. If you try:
CASE something WHEN 1 THEN 0 ELSE 'x' END
this will fail, when something is not 1, because this CASE expression
returns an integer value, as integer is higher than char in the
data-type precedence in SQL Server.
> I almost forgot; why is the cursorloop broken in the first place? There
> was no error in trigger, unless RETURN is considered an error!
Was there a ROLLBACK? A rollback in a trigge aborts execution.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx
Cursor loop is broken
from Table1. Each record in the cursor is inserted into Table2.
Insert trigger on Table2 is inserting the record into Table3 (in
another DB).
In the insert trigger on Table3, a series of checks are done on the
inserted record and in case of an error, an email is sent and the
trigger returns.
This break the cursorloop in SP1 and the rest of the records in the
cursor is not treated.
How do I make sure that all records are treated?
This is the flow:
-- SP1 ----------
DECLARE csrListe CURSOR FOR SELECT felt1 FROM Table1
OPEN csrListe
-- The first record is treated here...
:
-- Treat the rest
WHILE @.@.FETCH_STATUS = 0 BEGIN
FETCH NEXT FROM csrListe INTO @.feltet
IF @.@.FETCH_STATUS = 0 BEGIN
blah-blah-blah
INSERT INTO Table2 (Ordrenr, Status, Dato, Resultat) VALUES
(@.Ordrenr, @.Status, @.Dato, @.Result)
END
END
CLOSE csrListe
DEALLOCATE csrListe
-- Table2_ITrig ----------
INSERT INTO db2.dbo.Table3 SELECT * FROM inserted
-- Table3_ITrig ----------
SET NOCOUNT ON
DECLARE @.STATUS int
DECLARE @.DATOTID smalldatetime
DECLARE @.RESULT int
SELECT @.ORDRENR = (SELECT ORDRENR FROM INSERTED)
SELECT @.STATUS = (SELECT STATUS FROM INSERTED)
SELECT @.DATOTID = (SELECT DATO FROM INSERTED)
SELECT @.RESULT = (SELECT RESULT FROM INSERTED)
SET XACT_ABORT ON
IF NOT @.STATUS IN (1,2,3,4,5,6,9,10) BEGIN
SELECT @.ERR = 'ERROR - unknown status = ' + CAST(@.ORDRENR as char(4))
UPDATE Table3 SET RESULTAT=2 WHERE ORDRENUMMER=@.ORDRENR
EXEC @.rc = master.dbo.xp_smtp_sendmail
@.FROM = N...@.here.dk',
@.TO = N...@.here.dk',
@.priority = N'HIGH',
@.subject = N'Status error',
@.message = N'Status error',
@.type = N'text/plain',
@.server = 'smtp.here.dk'
RETURN
END
The mail is send so it must be the final RETURN that is causing the
trouble.Sren Larsen (sblar1@.surfpost.dk) writes:
> In a stored procedure (SP1) I am looping through a cursor with records
> from Table1. Each record in the cursor is inserted into Table2.
> Insert trigger on Table2 is inserting the record into Table3 (in
> another DB).
> In the insert trigger on Table3, a series of checks are done on the
> inserted record and in case of an error, an email is sent and the
> trigger returns.
> This break the cursorloop in SP1 and the rest of the records in the
> cursor is not treated.
> How do I make sure that all records are treated?
An error in a trigger aborts the batch. Thus, in SQL 2000, there is no
way to handle the situation in T-SQL, you would need to have a client
program that reacts on the error, and restarts the loop, but leaving
out the row that causes problems. In SQL 2005, you could use TRY-CATCH
to handle the situation.
But why are you running a loop in the first place? The normal procedure
to insert rows from one table to another is to say:
INSERT tbl2 (...)
SELECT ...
FROM tbl1
Of course, this would mean that if any of the rows are erroneous, then
all rows inserted would be rolled back by the trigger on Table3. But this
can be handled in different ways. (But exactly how, it's difficult to
say as I don't know the business requirements.)
The reason you should insert all, and not run a cursor, is that performance
for a cursor can be disastrous. If we are talking less than < 100 rows, it's
may be not that big deal. If we are talking 10000 rows, it can mean a
difference in processing time of 30 minutes instead of 30 seconds.
> -- Table3_ITrig ----------
> SET NOCOUNT ON
>
> DECLARE @.STATUS int
> DECLARE @.DATOTID smalldatetime
> DECLARE @.RESULT int
>
> SELECT @.ORDRENR = (SELECT ORDRENR FROM INSERTED)
> SELECT @.STATUS = (SELECT STATUS FROM INSERTED)
> SELECT @.DATOTID = (SELECT DATO FROM INSERTED)
> SELECT @.RESULT = (SELECT RESULT FROM INSERTED)
This trigger is poorly implemented. A trigger fires once per statement,
and must be able to handle multi-row operations.
--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx
Cursor Loop
w
previous w
below but it will only drop the wk214 table as calculated and does not carry
on to drop wk213,wk212 etc.
Does anybody know how I can acheive this?
Begin
DECLARE lcurTables_To_Be_Deleted CURSOR FOR
SELECT substring(NAME,28,3) FROM SNAPS_ARC..SYSOBJECTS(nolock) WHERE NAME
like @.vchArchiveTable_To_Delete and xtype = 'U' order by crdate desc
OPEN lcurTables_To_Be_Deleted
FETCH lcurTables_To_Be_Deleted into @.TabNoToDrop
SELECT @.TableNumToDrop = convert(int, @.TabNoToDrop) -- wk215
PRINT '1'
PRINT @.TableNumToDrop
SELECT @.TableNumToDrop = + convert(varchar,(@.TableNumToDrop - 1))
PRINT '2' -- wk214
PRINT @.TableNumToDrop
while @.@.fetch_status = 0
begin
EXEC('DROP TABLE SNAPS_ARC..' + @.vchArchiveTable_To_Delete1 + '_'
+ @.TableNumToDrop)
PRINT '_______________________________________
_________'
PRINT @.vchArchiveTable_To_Delete1 + '_' + @.TableNumToDrop + '
Dropped.' PRINT ''
FETCH lcurTables_To_Be_Deleted into @.TableToDrop
end
close lcurTables_To_Be_Deleted
deallocate lcurTables_To_Be_Deleted
EndMake sure you declare the cursor insensitive. Also, did you initialize all
your variables?
Seriously though, why would you want to prolong the life of such a poor
design by developing more code like this? This is so abysmal it breaks just
about every rule in the book: cursors; dynamic SQL; use of system tables;
modifying metadata. Maybe you aren't concerned, but this sort of thing
shouldn't get past even the most basic audit or compliance review.
How about:
DELETE FROM SomeTable
WHERE the_date < @.some_date
Simpler, no?
Take care.
David Portas
SQL Server MVP
--|||I have had this debate before David.
My new model design is in the pipeline with management.
Until then I am stuck with this.
The issue I have is why when the part that calculates the w
it goes into the loop. But it only goes in once. Have I missed something
blatent in the code that prevents it from going into the loop for the other
tables returned from the cursor definition
"David Portas" wrote:
> Make sure you declare the cursor insensitive. Also, did you initialize all
> your variables?
> Seriously though, why would you want to prolong the life of such a poor
> design by developing more code like this? This is so abysmal it breaks jus
t
> about every rule in the book: cursors; dynamic SQL; use of system tables;
> modifying metadata. Maybe you aren't concerned, but this sort of thing
> shouldn't get past even the most basic audit or compliance review.
> How about :
> DELETE FROM SomeTable
> WHERE the_date < @.some_date
> Simpler, no?
> Take care.
> --
> David Portas
> SQL Server MVP
> --
>|||> My new model design is in the pipeline with management.
Good news :-)
I haven't tested it out but I suspect the cursor terminates because dropping
the table deletes the current row. That's why I suggested you declare the
cursor INSENSITIVE. Alternatively, select the table names into a table
variable and iterate through that.
Again, note that you really should avoid system tables where you can. For
this I would prefer to use INFORMATION_SCHEMA.TABLES.
Hope this helps.
David Portas
SQL Server MVP
--
"marcmc" wrote:
> I have had this debate before David.
> My new model design is in the pipeline with management.
> Until then I am stuck with this.
> The issue I have is why when the part that calculates the w
un
> it goes into the loop. But it only goes in once. Have I missed something
> blatent in the code that prevents it from going into the loop for the othe
r
> tables returned from the cursor definition
>
> "David Portas" wrote:
>|||I execute ...
exec uspDB_Maint_Archive_Snaps 'FAT_SNAP_PO_RISK_DETAIL_mth', 216, 'DbName'
Then I declare cursor...
Begin
declare lcurTables_To_Be_Deleted cursor for
select substring(NAME,28,3) from SNAPS_ARC..SYSOBJECTS(nolock) where name
like @.vchArchiveTable_To_Delete and xtype = 'U' order by crdate desc
open lcurTables_To_Be_Deleted
fetch lcurTables_To_Be_Deleted into @.TabNoToDrop
This brings the following into the cursor
--
215
214
213
212
212
I want to keep 215 but delete the rest
I want the next few lines of to do this. But I cant seem to find a way.
Please help...
SELECT @.TableNumToDrop = convert(int, @.TabNoToDrop) -- 215
SELECT @.TableNumToDrop = + convert(varchar,(@.TableNumToDrop - 1))
SELECT @.TableToDrop = @.vchArchiveTable_To_Delete1 + '_' + @.TableNumToDrop
while @.@.fetch_status = 0
begin
PRINT @.vchArchiveTable_To_Delete1 + '_' + @.TabNoToDrop
EXEC('DROP TABLE SNAPS_ARC..' + @.vchArchiveTable_To_Delete1 + '_' +
@.TabNoToDrop)
PRINT '_______________________________________
_________'
PRINT @.vchArchiveTable_To_Delete1 + '_' + @.TabNoToDrop + ' Dropped.'
PRINT ''
FETCH lcurTables_To_Be_Deleted into @.TabNoToDrop
end
close lcurTables_To_Be_Deleted
deallocate lcurTab|||On Mon, 9 May 2005 02:54:01 -0700, marcmc wrote:
>Hi, I wonder can someone help me.
(snip)
Hi marcmc,
Since you are already aware of the downsides of this design, and
battling management to get it changed, I won't comment on that...
In your code, you use three almost but not quite equally named
variables: @.TabNoToDrop, @.TableNumToDrop and @.TableToDrop. The first and
third seem to server the same purpose (the first is used in the first
FETCH and the third in the FETCH in the WHILE loop). The second includes
only a part of the table name and is calculated from the first after the
first FETCH. Since it is not recalculated after the FETCH in the WHILE
loop, it's value never changes, and you are just attempting to drop the
same table over and over again.
>Begin
> DECLARE lcurTables_To_Be_Deleted CURSOR FOR
> SELECT substring(NAME,28,3) FROM SNAPS_ARC..SYSOBJECTS(nolock) WHERE NAME
>like @.vchArchiveTable_To_Delete and xtype = 'U' order by crdate desc
> OPEN lcurTables_To_Be_Deleted
> FETCH lcurTables_To_Be_Deleted into @.TabNoToDrop
> SELECT @.TableNumToDrop = convert(int, @.TabNoToDrop) -- wk215
> PRINT '1'
> PRINT @.TableNumToDrop
> SELECT @.TableNumToDrop = + convert(varchar,(@.TableNumToDrop - 1))
> PRINT '2' -- wk214
> PRINT @.TableNumToDrop
> while @.@.fetch_status = 0
> begin
> EXEC('DROP TABLE SNAPS_ARC..' + @.vchArchiveTable_To_Delete1 + '_'
>+ @.TableNumToDrop)
> PRINT '_______________________________________
_________'
> PRINT @.vchArchiveTable_To_Delete1 + '_' + @.TableNumToDrop + '
>Dropped.' PRINT ''
> FETCH lcurTables_To_Be_Deleted into @.TableToDrop
> end
> close lcurTables_To_Be_Deleted
> deallocate lcurTables_To_Be_Deleted
>End
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)