Calculating distance between 2 zips by using a function - sql-server

I have a table of which first 3 rows look like:
ship_to_zip Knoxville_Zip Phoenix_Zip
52773 37909 85009
46341 37909 85009
83114 37909 85009
I have a function that calculates distance in miles between 2 zips: dbo.ufnzipcodedist_2012(zip1,zip2)
Now I want to add 2 more columns to my table: Miles_from_Knoxville and Miles_from_Phoenix, each which calculates miles between ship_to_id and Knoxville_Zip/Phoenix_Zip respectively.
I tried below:
select IDENTITY(Int,1,1) ID,*,CAST(0 as float) dist1,CAST(0 as FLOAT) DIST2
INTO #TEMP
from #zip
declare #COUNT INT
DECLARE #DIST1 FLOAT
DECLARE #DIST2 FLOAT
set #COUNT=1
while (#COUNT<=2)
begin
SELECT #DIST1=dbo.ufnzipcodedist_2012(SHIP_TO_ZIP,KNOXVILLE_ZIP)
,#DIST2=dbo.ufnzipcodedist_2012(SHIP_TO_ZIP,PHOENIX_ZIP)
FROM #TEMP
UPDATE t SET T.DIST1=#DIST1,t.DIST2=#DIST2
FROM #TEMP t
WHERE ID=#COUNT
set #COUNT=#COUNT+1
end
It is going into a infinite loop and columns DIST1, DIST2 are populated with 0s. Where did I go wrong?

Please Modify your query as below:
SELECT IDENTITY(INT, 1, 1) ID
,*
,CAST(0 AS FLOAT) dist1
,CAST(0 AS FLOAT) DIST2
INTO #TEMP
FROM #zip
DECLARE #COUNT INT
,#DIST1 FLOAT
,#DIST2 FLOAT
,#MAXID INT
SET #COUNT = 1
SELECT #MAXID = MAX(ID)
FROM #TEMP
WHILE (#COUNT <= #MAXID)
BEGIN
SELECT #DIST1 = dbo.ufnzipcodedist_2012(z1, z2)
,#DIST2 = dbo.ufnzipcodedist_2012(z2, z3)
FROM #TEMP
WHERE ID = #COUNT
UPDATE t
SET T.DIST1 = #DIST1
,t.DIST2 = #DIST2
FROM #TEMP t
WHERE ID = #COUNT
SET #COUNT = #COUNT + 1
END
SELECT *
FROM #TEMP
Here is a link to SQL fiddle:http://sqlfiddle.com/#!6/b5699/3

Related

Trigger did not run?

I have a trigger "after insert/update/delete/". It is supposed to count Balance on Account table based on transactions in Transaction table. It is on Transaction table. I am getting Balance discrepancies rarely, so have decided to add some logging into it. It dumps inserted+deleted tables (they are combined into a table var) and tsql statement which fired it. Judging from my log, it looks like the trigger did not fire for some inserts into Transaction table. Can this happen ? Are there any TSQL statement which change table data without firing trigger (except truncate table etc)?
Here is the trigger :
CREATE TRIGGER [dbo].[trg_AccountBalance]
ON [dbo].[tbl_GLTransaction]
AFTER INSERT, UPDATE, DELETE
AS
set nocount on
begin try
declare #OldOptions int = ##OPTIONS
set xact_abort off
declare #IsDebug bit = 1
declare #CurrentDateTime datetime = getutcdate()
declare #TriggerMessage varchar(max), #TriggerId int
if #IsDebug = 1
begin
select #TriggerId = isnull(max(TriggerId), 0) + 1
from uManageDBLogs.dbo.tbl_TriggerLog
declare #dbcc_INPUTBUFFER table(EventType nvarchar(30), Parameters Int, EventInfo nvarchar(4000) )
declare #my_spid varchar(20) = CAST(##SPID as varchar(20))
insert #dbcc_INPUTBUFFER
exec('DBCC INPUTBUFFER ('+#my_spid+')')
select #TriggerMessage = replace(EventInfo, '''', '''''') from #dbcc_INPUTBUFFER
insert into uManageDBLogs.dbo.tbl_TriggerLog (TriggerId, "Message", CreateDate)
values (#TriggerId, #TriggerMessage, #CurrentDateTime)
end
declare #Oper int
select #Oper = 0
-- determine type of sql statement
if exists (select * from inserted) select #Oper = #Oper + 1
if exists (select * from deleted) select #Oper = #Oper + 2
if #IsDebug = 1
begin
select #TriggerMessage = '#Oper = ' + convert(varchar, #Oper)
insert into uManageDBLogs.dbo.tbl_TriggerLog (TriggerId, "Message", CreateDate)
values (#TriggerId, #TriggerMessage, #CurrentDateTime)
end
if #Oper = 0 return -- No data changed
declare #TomorrowDate date = dateadd(day, 1, convert(date, getdate()))
declare #CurrentDate date = convert(date, getdate())
-- transactions from both inserted and deleted tables
declare #tbl_Trans table (FirmId int, GLAccountId int,
AmountDebit money, AmountCredit money, "Status" char(1), TableType char(1))
declare #tbl_AccountCounters table (FirmId int, GLAccountId int, Balance money)
declare #IsChange bit = null
insert into #tbl_Trans (FirmId, GLAccountId, AmountDebit, AmountCredit, "Status", TableType)
select FirmId, GLAccountId, AmountDebit, AmountCredit, "Status", 'I'
from inserted
union
select FirmId, GLAccountId, AmountDebit, AmountCredit, "Status", 'D'
from deleted
if #IsDebug = 1
begin
select #TriggerMessage = (select * from #tbl_Trans for xml path ('tbl_Trans'))
insert into uManageDBLogs.dbo.tbl_TriggerLog (TriggerId, "Message", CreateDate)
values (#TriggerId, #TriggerMessage, #CurrentDateTime)
end
insert into #tbl_AccountCounters (FirmId, GLAccountId, Balance)
select FirmId, GLAccountId, 0
from #tbl_Trans
group by FirmId, GLAccountId
if #Oper = 1 or #Oper = 2 -- insert/delete
begin
update #tbl_AccountCounters
set Balance = cnt.TransSum
from #tbl_AccountCounters as ac join
(
select trans.FirmId, trans.GLAccountId,
isnull(sum((trans.AmountDebit - trans.AmountCredit) * iif(trans.TableType = 'I', 1, -1)), 0) as TransSum
from #tbl_Trans as trans
where trans.Status = 'A'
group by trans.FirmId, trans.GLAccountId
) as cnt on ac.FirmId = cnt.FirmId and ac.GLAccountId = cnt.GLAccountId
select #IsChange = 1
end
else
begin
if update(AmountDebit) or update(AmountCredit) or update(Status) or update(GLAccountId)
begin
update #tbl_AccountCounters
set Balance = cnt.TransBalance
from #tbl_AccountCounters as ac join
(select trans.FirmId, trans.GLAccountId, isnull(sum(trans.AmountDebit - trans.AmountCredit), 0) as TransBalance
from dbo.tbl_GLTransaction as trans
where trans."Status" = 'A' and exists (select 1 from #tbl_AccountCounters as ac
where ac.GLAccountId = trans.GLAccountId and ac.FirmId = trans.FirmId)
group by trans.FirmId, trans.GLAccountId) as cnt on
ac.FirmId = cnt.FirmId and ac.GLAccountId = cnt.GLAccountId
select #IsChange = 0
end
end
if #IsDebug = 1
begin
select #TriggerMessage = '#IsChange = ' + isnull(convert(varchar, #IsChange), 'null')
insert into uManageDBLogs.dbo.tbl_TriggerLog (TriggerId, "Message", CreateDate)
values (#TriggerId, #TriggerMessage, #CurrentDateTime)
select #TriggerMessage = (select * from #tbl_AccountCounters for xml path ('tbl_AccountCounters'))
insert into uManageDBLogs.dbo.tbl_TriggerLog (TriggerId, "Message", CreateDate)
values (#TriggerId, #TriggerMessage, #CurrentDateTime)
end
if #IsChange is not null
begin
update tbl_GLAccount
set tbl_GLAccount.Balance = iif(#IsChange = 1, cnt.Balance + acc.Balance, cnt.Balance),
tbl_GLAccount.LastUpdate = getutcdate(),
tbl_GLAccount.LastUpdatedBy = 1
from #tbl_AccountCounters as cnt join dbo.tbl_GLAccount as acc on
cnt.FirmId = acc.FirmId and cnt.GLAccountId = acc.GLAccountId
end
if (16384 & #OldOptions) = 16384 set xact_abort on
end try
begin catch
declare #ErrorLine varchar(max)
select #ErrorLine = uManageDb.dbo.udf_GetErrorInfo()
insert into uManageDb.dbo.tbl_TriggerError ("Name", "Message", CreateDate)
values ('AccountingDB..trg_AccountBalance', #ErrorLine, GETUTCDATE())
end catch
I think I've found it. I have this line:
select .. from inserted
union
select .. from deleted
and they inserted 5 trans for $300 and 4 trans $100. I've got 2 records (300 and 100) in my #tbl_Trans (it was in the log). That's probably was the bug. So log hellps and trigger run as it had to.
I'll replace union with union all.

How to convert a bigint to float

I know that a bigint should implicitly convert to a float but it does not seem to.
Table column to be updated:
[GBUsed] [float] NOT NULL,
Example of data in that column:
430.5
Logic: I'm summing 2 bigint columns together and dividing by 1024. An example of 1 of the row - I get: 1545
I the update the GBUsed column which is defined as float but it does not convert. I still get the 1545.
Stored procedure:
CREATE PROCEDURE [dbo].[RecalculateBandwidthUsage]
AS
BEGIN
SET NOCOUNT ON;
DECLARE #RowCount int,
#Rc int,
#Message varchar(max),
#CurrentDateTime datetime
CREATE TABLE #Temp
(
SwitchID int,
PortIndex int,
SwitchIP varchar(50),
GBUsed bigint
)
SET #CurrentDateTime = GETDATE()
-- FOR TESTING:
BEGIN TRANSACTION
INSERT #Temp (SwitchID, PortIndex, SwitchIP, GBUsed)
SELECT
c.SwitchID, c.PortIndex,
s.SwitchIP,
SUM ((c.BandwidthIn + c.BandwidthOut) / 1024) AS GBUsed -- converting to gigabytes
FROM
dbo.BandwidthLogCalculatedTest6 c
INNER JOIN
Switch s ON (c.SwitchID = s.SwitchID)
WHERE
(c.StartDate < DATEADD(HOUR, -1, #CurrentDateTime)
AND c.EntryType = 'Second')
GROUP BY
c.SwitchID, c.PortIndex, s.SwitchIP
ORDER BY
c.PortIndex
SELECT
#Rc = ##ERROR,
#RowCount = ##ROWCOUNT
IF #Rc <> 0
BEGIN
SELECT #Message = 'Critical Error - procedure RecalculateBandwidthUsage - on select. Return code: ' + Cast(#Rc as varchar)
RAISERROR (#Message, 16, 1)
END
-- FOR TESTING:
SELECT 'Temp table '
SELECT *
FROM #temp
ORDER BY PortIndex
IF #RowCount > 0
BEGIN
-- FOR TESTING:
SELECT 'Before update '
SELECT b.SwitchIP, b.SwitchPort, b.GBUsed
FROM dbo.Bandwidth b
INNER JOIN #temp t ON (b.SwitchIP = t.SwitchIP AND b.SwitchPort = t.PortIndex )
ORDER BY b.SwitchPort
-- Update.
UPDATE dbo.Bandwidth
SET GBUsed = CONVERT(float, t.Gbused)
FROM #Temp t
WHERE (Bandwidth.SwitchIP = t.SwitchIP AND Bandwidth.SwitchPort = t.PortIndex)
SELECT #Rc = ##ERROR
IF #Rc <> 0
BEGIN
SELECT #Message = 'Critical Error - procedure RecalculateBandwidthUsage - on Bandwidth update. Return code: ' + Cast(#Rc as varchar)
RAISERROR (#Message, 16, 1)
END
-- FOR TESTING:
SELECT 'After update '
SELECT b.SwitchIP, b.SwitchPort, b.GBUsed
FROM dbo.Bandwidth b
INNER JOIN #temp t ON (b.SwitchIP = t.SwitchIP AND b.SwitchPort = t.PortIndex)
ORDER BY b.SwitchPort
END
ROLLBACK TRANSACTION
END
You are doing an integer division - so therefore, your result will also be an integer (or BIGINT).
You need to use this code in order to get fractional values:
SUM ((c.BandwidthIn + c.BandwidthOut) / 1024.0) AS GBUsed
Dividing by 1024.0 (instead of just 1024) will make sure to use fractional values

How to fix this logic?

i have a query with 3 variable tables: #result, #order and #stock.
the logic is the stock qty must be allocated by lotsize (here i set=1) to all order based on priority (FIFO). the stock qty must be allocated till zero and the allocateqty must <= orderqty. the problem is one of orders, its allocateqty is over orderqty (priority=7) while other are correct.
DECLARE #RESULT TABLE (priority int,partcode nvarchar(50),orderqty int, runningstock int, allocateqty int)
DECLARE #ORDER TABLE(priority int,partcode nvarchar(50),orderqty int)
DECLARE #STOCK TABLE(partcode nvarchar(50),stockqty int)
INSERT INTO #ORDER (priority,partcode,orderqty)
VALUES (1,'A',10),
(2,'A',50),
(3,'A',10),
(4,'A',40),
(5,'A',3),
(6,'A',5),
(7,'A',11),
(8,'A',10),
(9,'A',10),
(10,'A',10);
INSERT INTO #STOCK(partcode,stockqty)
VALUES('A',120)
IF (SELECT SUM(orderqty)FROM #ORDER)<(SELECT stockqty FROM #STOCK)
BEGIN
INSERT INTO #RESULT(priority,partcode,orderqty,allocateqty)
SELECT priority, partcode,orderqty,orderqty
FROM #ORDER
END
ELSE
BEGIN
DECLARE #allocatedqty int = 0
DECLARE #Lotsize int=1
DECLARE #allocateqty int = #Lotsize
DECLARE #runningstock int = (SELECT stockqty FROM #stock)
WHILE #runningstock>=0
BEGIN
DECLARE #priority int
SELECT TOP 1 #priority = priority FROM #order ORDER BY priority ASC
WHILE #priority <= (SELECT MAX(priority) FROM #order)
BEGIN
DECLARE #orderqty int
SELECT #orderqty = orderqty - #allocatedqty FROM #order WHERE priority = #priority
SELECT #allocateqty = CASE WHEN #runningstock > 0 AND #orderqty > 0 THEN #Lotsize ELSE 0 END
INSERT INTO #RESULT(priority,partcode,orderqty,runningstock,allocateqty)
SELECT #priority,
partcode,
CASE WHEN #orderqty >= 0 THEN #orderqty ELSE 0 END AS orderqty,
#runningstock,
#allocateqty
FROM #order
WHERE priority = #priority
SET #priority += 1
SET #runningstock = #runningstock - #allocateqty
END
SET #allocatedqty += #allocateqty
IF (#runningstock <= 0) BREAK
END
END
select * from #RESULT where priority=7;
SELECT priority,
sum(allocateqty) as allocated
from #RESULT
group by priority
the result:
my reputation not reach 50 so cant add comment.
you said your other order is correct then priority = 7 is also correct. you can compare priority 2 and 4 with 7. its the same thing. i think all of your loop for orderqty only reach 10 times where priority 7 got 11 so it will left 1.
Either everything is correct or everything is wrong =x
EDIT:
Hi, I found the answer.
Change
SET #allocatedqty += #allocateqty
to
SET #allocatedqty += 1
because when using SET #allocatedqty += #allocateqty, the last order #allocateqty is 0 then it will always make #allocatedqty = 0 then it will not increase.
Hope this really help you.
EDIT based on #Jesuraja given answer it should be:
SET #allocatedqty += #Lotsize
As I'm not quite sure what you try to achieve with records which will set your stock to 0 or beyond I just can provide this. But it is much better than to run all your orders in a loop. Maybe you'll want to replace your loop.
DECLARE #RESULT TABLE (priority int,partcode nvarchar(50),orderqty int, runningstock int, allocateqty int)
DECLARE #ORDER TABLE(priority int,partcode nvarchar(50),orderqty int)
DECLARE #STOCK TABLE(partcode nvarchar(50),stockqty int)
INSERT INTO #ORDER (priority,partcode,orderqty)
--VALUES (1,'A',10),(2,'A',50),(3,'A',10),(4,'A',40),(5,'A',3),(6,'A',5),(7,'A',11),(8,'A',10),(9,'A',10),(10,'A',10); --your orders
VALUES (1,'A',1),(2,'A',2),(3,'A',3),(4,'A',4),(5,'A',5),(6,'A',6),(7,'A',7),(8,'A',8),(9,'A',9),(10,'A',10);
INSERT INTO #STOCK(partcode,stockqty)
--VALUES('A',50) -- your stock
VALUES('A',50)
IF (SELECT SUM(orderqty) FROM #ORDER)<(SELECT stockqty FROM #STOCK)
BEGIN
INSERT INTO #RESULT(priority,partcode,orderqty,allocateqty)
SELECT priority, partcode,orderqty,orderqty
FROM #ORDER
END
ELSE
BEGIN
;WITH dat AS(
SELECT s.partcode, s.stockqty, o.priority, o.orderqty,
ROW_NUMBER() OVER(PARTITION BY s.partcode ORDER BY o.priority DESC) as runningOrder
FROM #Stock as s
INNER JOIN #ORDER as o
ON s.partcode = o.partcode
)
INSERT INTO #RESULT(priority,partcode,orderqty,runningstock,allocateqty)
SELECT d1.priority, d1.partcode, d1.orderqty,
d1.stockqty - SUM(d2.orderqty) OVER(PARTITION BY d1.runningOrder) as runningstock,
CASE WHEN d1.stockqty - SUM(d2.orderqty) OVER(PARTITION BY d1.runningOrder) > 0 AND d1.orderqty > 0 THEN 1 ELSE 0 END
FROM dat as d1
INNER JOIN dat as d2
ON d1.partcode = d2.partcode
AND d1.runningOrder >= d2.runningOrder
END
select * from #RESULT where priority=7;
SELECT priority,
sum(allocateqty) as allocated
from #RESULT
group by priority

Insert statement with random generated number

What I'm trying to accomplish is to assign a 5 digit number to a row in the table and insert that value with column value to a different table.
For example, this query returns all the rows that I would like to assign a 5 digit random ID:
SELECT DISTINCT(ExternalAgentId) FROM lOGS_V WHERE EXTERNALAGENTID <> ''
Currently it's returning 4600 rows. NOTE* ExternalAgentID is varchar(50)
What I need to do is assign a random 5 digit number between 10001 and 39999. Once I generate the number insert it to the table with ExternalAgentId from previous query to another table.
Here's the approach I took:
DECLARE #randAgentID int;
DECLARE #AgentID int;
DECLARE #MIN INT;
DECLARE #MAX INT;
SET #MIN = 10001
SET #MAX = 39999
SELECT #randAgentID = ROUND(((#MAX - #MIN -1) * RAND() + #MIN), 0)
SELECT #AgentID = InternalAgentID FROM VendorAgentIDs where InternalAgentID = #randAgentID
IF #AgentID is null
BEGIN
INSERT INTO VendorAgentIDs (VendorID, TRIAgentID) values (SELECT DISTINCT(ExternalAgentId) FROM LOGS_V WHERE EXTERNALAGENTID <> '', #randAgentID)
END
ELSE
BEGIN
SELECT #randAgentID = ROUND(((#MAX - #MIN -1) * RAND() + #MIN), 0)
INSERT INTO VendorAgentIDs (VendorID, TRIAgentID) values (SELECT DISTINCT(ExternalAgentId) FROM LOGS_V WHERE EXTERNALAGENTID <> '', #randAgentID)
END
It's generating random 5 digit number correctly. However, I'm having two issues:
I have a syntax error in my insert statements.
...values (SELECT DISTINCT(ExternalAgentId)...
If the randAgentID exists in the table, it goes to the ELSE statement. I know the chances are low, but what if the next randAgentID also exists in the table? How can I prevent that?
The table VendorAgentIDs has three columns.
ID (autoincrement)
VendorID (varchar(50))
InternalAgentID (PK, int)
Any suggestions on how I can resolve the above two issues?
Thanks
* *UPDATE
Based on the suggestion, I edited my code. However, I now have a violation of PRIMARY KEY.
DECLARE #randAgentID int;
DECLARE #AgentID int;
DECLARE #MIN INT;
DECLARE #MAX INT;
SET #MIN = 10001
SET #MAX = 39999
SET #AgentID = 1
WHILE #AgentID IS NOT NULL
BEGIN
SET #AgentID = NULL
SELECT #randAgentID = ROUND(((#MAX - #MIN -1) * RAND() + #MIN), 0)
INSERT INTO VendorAgentIDs (VendorAgentID, InternalAgentID) SELECT DISTINCT(ExternalAgentId), #randAgentID FROM LOGS_V WHERE EXTERNALAGENTID <> ''
SELECT #AgentID = InternalAgentID FROM VendorAgentIDs where InternalAgentID = #randAgentID
END
Violation of PRIMARY KEY constraint 'PK_VendorAgentIDs'. Cannot insert duplicate key in object 'dbo.VendorAgentIDs'.
May be this will solve your PK issue
INSERT INTO VendorAgentIDs
(VendorAgentID,InternalAgentID)
SELECT DISTINCT ExternalAgentId,#randAgentID
FROM LOGS_V
WHERE EXTERNALAGENTID <> ''
AND ExternalAgentId NOT IN (SELECT VendorAgentID
FROM VendorAgentIDs)
INSERT INTO VendorAgentIDs (VendorID, TRIAgentID) values (SELECT DISTINCT(ExternalAgentId) FROM TRI_PORTAL.DBO.SCREENPOPLOGS_V WHERE EXTERNALAGENTID <> '', #randAgentID)
Is invalid SQL. However I think you can do
INSERT INTO VendorAgentIDs (VendorID, TRIAgentID) SELECT DISTINCT(ExternalAgentId), #randAgentID FROM TRI_PORTAL.DBO.SCREENPOPLOGS_V WHERE EXTERNALAGENTID <> ''
As for the possiblity (eventuality) of a collision you should just do a loop. It becomes increasingly inefficient but if it has to be a random number and not an index then, so be it.
SET #AgentID = 1
WHILE #AgentID is not null
BEGIN
SET #AgentID = NULL
SELECT #randAgentID = ROUND(((#MAX - #MIN -1) * RAND() + #MIN), 0)
SELECT #randAgentID -- why is this here?
SELECT #AgentID = InternalAgentID FROM VendorAgentIDs where InternalAgentID = #randAgentID
END

Is there a way to loop through a table variable in TSQL without using a cursor?

Let's say I have the following simple table variable:
declare #databases table
(
DatabaseID int,
Name varchar(15),
Server varchar(15)
)
-- insert a bunch rows into #databases
Is declaring and using a cursor my only option if I wanted to iterate through the rows? Is there another way?
First of all you should be absolutely sure you need to iterate through each row — set based operations will perform faster in every case I can think of and will normally use simpler code.
Depending on your data it may be possible to loop using just SELECT statements as shown below:
Declare #Id int
While (Select Count(*) From ATable Where Processed = 0) > 0
Begin
Select Top 1 #Id = Id From ATable Where Processed = 0
--Do some processing here
Update ATable Set Processed = 1 Where Id = #Id
End
Another alternative is to use a temporary table:
Select *
Into #Temp
From ATable
Declare #Id int
While (Select Count(*) From #Temp) > 0
Begin
Select Top 1 #Id = Id From #Temp
--Do some processing here
Delete #Temp Where Id = #Id
End
The option you should choose really depends on the structure and volume of your data.
Note: If you are using SQL Server you would be better served using:
WHILE EXISTS(SELECT * FROM #Temp)
Using COUNT will have to touch every single row in the table, the EXISTS only needs to touch the first one (see Josef's answer below).
Just a quick note, if you are using SQL Server (2008 and above), the examples that have:
While (Select Count(*) From #Temp) > 0
Would be better served with
While EXISTS(SELECT * From #Temp)
The Count will have to touch every single row in the table, the EXISTS only needs to touch the first one.
This is how I do it:
declare #RowNum int, #CustId nchar(5), #Name1 nchar(25)
select #CustId=MAX(USERID) FROM UserIDs --start with the highest ID
Select #RowNum = Count(*) From UserIDs --get total number of records
WHILE #RowNum > 0 --loop until no more records
BEGIN
select #Name1 = username1 from UserIDs where USERID= #CustID --get other info from that row
print cast(#RowNum as char(12)) + ' ' + #CustId + ' ' + #Name1 --do whatever
select top 1 #CustId=USERID from UserIDs where USERID < #CustID order by USERID desc--get the next one
set #RowNum = #RowNum - 1 --decrease count
END
No Cursors, no temporary tables, no extra columns.
The USERID column must be a unique integer, as most Primary Keys are.
Define your temp table like this -
declare #databases table
(
RowID int not null identity(1,1) primary key,
DatabaseID int,
Name varchar(15),
Server varchar(15)
)
-- insert a bunch rows into #databases
Then do this -
declare #i int
select #i = min(RowID) from #databases
declare #max int
select #max = max(RowID) from #databases
while #i <= #max begin
select DatabaseID, Name, Server from #database where RowID = #i --do some stuff
set #i = #i + 1
end
Here is how I would do it:
Select Identity(int, 1,1) AS PK, DatabaseID
Into #T
From #databases
Declare #maxPK int;Select #maxPK = MAX(PK) From #T
Declare #pk int;Set #pk = 1
While #pk <= #maxPK
Begin
-- Get one record
Select DatabaseID, Name, Server
From #databases
Where DatabaseID = (Select DatabaseID From #T Where PK = #pk)
--Do some processing here
--
Select #pk = #pk + 1
End
[Edit] Because I probably skipped the word "variable" when I first time read the question, here is an updated response...
declare #databases table
(
PK int IDENTITY(1,1),
DatabaseID int,
Name varchar(15),
Server varchar(15)
)
-- insert a bunch rows into #databases
--/*
INSERT INTO #databases (DatabaseID, Name, Server) SELECT 1,'MainDB', 'MyServer'
INSERT INTO #databases (DatabaseID, Name, Server) SELECT 1,'MyDB', 'MyServer2'
--*/
Declare #maxPK int;Select #maxPK = MAX(PK) From #databases
Declare #pk int;Set #pk = 1
While #pk <= #maxPK
Begin
/* Get one record (you can read the values into some variables) */
Select DatabaseID, Name, Server
From #databases
Where PK = #pk
/* Do some processing here */
/* ... */
Select #pk = #pk + 1
End
If you have no choice than to go row by row creating a FAST_FORWARD cursor. It will be as fast as building up a while loop and much easier to maintain over the long haul.
FAST_FORWARD
Specifies a FORWARD_ONLY, READ_ONLY cursor with performance optimizations enabled. FAST_FORWARD cannot be specified if SCROLL or FOR_UPDATE is also specified.
This will work in SQL SERVER 2012 version.
declare #Rowcount int
select #Rowcount=count(*) from AddressTable;
while( #Rowcount>0)
begin
select #Rowcount=#Rowcount-1;
SELECT * FROM AddressTable order by AddressId desc OFFSET #Rowcount ROWS FETCH NEXT 1 ROWS ONLY;
end
Another approach without having to change your schema or using temp tables:
DECLARE #rowCount int = 0
,#currentRow int = 1
,#databaseID int
,#name varchar(15)
,#server varchar(15);
SELECT #rowCount = COUNT(*)
FROM #databases;
WHILE (#currentRow <= #rowCount)
BEGIN
SELECT TOP 1
#databaseID = rt.[DatabaseID]
,#name = rt.[Name]
,#server = rt.[Server]
FROM (
SELECT ROW_NUMBER() OVER (
ORDER BY t.[DatabaseID], t.[Name], t.[Server]
) AS [RowNumber]
,t.[DatabaseID]
,t.[Name]
,t.[Server]
FROM #databases t
) rt
WHERE rt.[RowNumber] = #currentRow;
EXEC [your_stored_procedure] #databaseID, #name, #server;
SET #currentRow = #currentRow + 1;
END
You can use a while loop:
While (Select Count(*) From #TempTable) > 0
Begin
Insert Into #Databases...
Delete From #TempTable Where x = x
End
Lightweight, without having to make extra tables, if you have an integer ID on the table
Declare #id int = 0, #anything nvarchar(max)
WHILE(1=1) BEGIN
Select Top 1 #anything=[Anything],#id=#id+1 FROM Table WHERE ID>#id
if(##ROWCOUNT=0) break;
--Process #anything
END
I really do not see the point why you would need to resort to using dreaded cursor.
But here is another option if you are using SQL Server version 2005/2008
Use Recursion
declare #databases table
(
DatabaseID int,
Name varchar(15),
Server varchar(15)
)
--; Insert records into #databases...
--; Recurse through #databases
;with DBs as (
select * from #databases where DatabaseID = 1
union all
select A.* from #databases A
inner join DBs B on A.DatabaseID = B.DatabaseID + 1
)
select * from DBs
-- [PO_RollBackOnReject] 'FININV10532'
alter procedure PO_RollBackOnReject
#CaseID nvarchar(100)
AS
Begin
SELECT *
INTO #tmpTable
FROM PO_InvoiceItems where CaseID = #CaseID
Declare #Id int
Declare #PO_No int
Declare #Current_Balance Money
While (Select ROW_NUMBER() OVER(ORDER BY PO_LineNo DESC) From #tmpTable) > 0
Begin
Select Top 1 #Id = PO_LineNo, #Current_Balance = Current_Balance,
#PO_No = PO_No
From #Temp
update PO_Details
Set Current_Balance = Current_Balance + #Current_Balance,
Previous_App_Amount= Previous_App_Amount + #Current_Balance,
Is_Processed = 0
Where PO_LineNumber = #Id
AND PO_No = #PO_No
update PO_InvoiceItems
Set IsVisible = 0,
Is_Processed= 0
,Is_InProgress = 0 ,
Is_Active = 0
Where PO_LineNo = #Id
AND PO_No = #PO_No
End
End
It's possible to use a cursor to do this:
create function [dbo].f_teste_loop
returns #tabela table
(
cod int,
nome varchar(10)
)
as
begin
insert into #tabela values (1, 'verde');
insert into #tabela values (2, 'amarelo');
insert into #tabela values (3, 'azul');
insert into #tabela values (4, 'branco');
return;
end
create procedure [dbo].[sp_teste_loop]
as
begin
DECLARE #cod int, #nome varchar(10);
DECLARE curLoop CURSOR STATIC LOCAL
FOR
SELECT
cod
,nome
FROM
dbo.f_teste_loop();
OPEN curLoop;
FETCH NEXT FROM curLoop
INTO #cod, #nome;
WHILE (##FETCH_STATUS = 0)
BEGIN
PRINT #nome;
FETCH NEXT FROM curLoop
INTO #cod, #nome;
END
CLOSE curLoop;
DEALLOCATE curLoop;
end
I'm going to provide the set-based solution.
insert #databases (DatabaseID, Name, Server)
select DatabaseID, Name, Server
From ... (Use whatever query you would have used in the loop or cursor)
This is far faster than any looping techique and is easier to write and maintain.
I prefer using the Offset Fetch if you have a unique ID you can sort your table by:
DECLARE #TableVariable (ID int, Name varchar(50));
DECLARE #RecordCount int;
SELECT #RecordCount = COUNT(*) FROM #TableVariable;
WHILE #RecordCount > 0
BEGIN
SELECT ID, Name FROM #TableVariable ORDER BY ID OFFSET #RecordCount - 1 FETCH NEXT 1 ROW;
SET #RecordCount = #RecordCount - 1;
END
This way I don't need to add fields to the table or use a window function.
I agree with the previous post that set-based operations will typically perform better, but if you do need to iterate over the rows here's the approach I would take:
Add a new field to your table variable (Data Type Bit, default 0)
Insert your data
Select the Top 1 Row where fUsed = 0 (Note: fUsed is the name of the field in step 1)
Perform whatever processing you need to do
Update the record in your table variable by setting fUsed = 1 for the record
Select the next unused record from the table and repeat the process
DECLARE #databases TABLE
(
DatabaseID int,
Name varchar(15),
Server varchar(15),
fUsed BIT DEFAULT 0
)
-- insert a bunch rows into #databases
DECLARE #DBID INT
SELECT TOP 1 #DBID = DatabaseID from #databases where fUsed = 0
WHILE ##ROWCOUNT <> 0 and #DBID IS NOT NULL
BEGIN
-- Perform your processing here
--Update the record to "used"
UPDATE #databases SET fUsed = 1 WHERE DatabaseID = #DBID
--Get the next record
SELECT TOP 1 #DBID = DatabaseID from #databases where fUsed = 0
END
Step1: Below select statement creates a temp table with unique row number for each record.
select eno,ename,eaddress,mobno int,row_number() over(order by eno desc) as rno into #tmp_sri from emp
Step2:Declare required variables
DECLARE #ROWNUMBER INT
DECLARE #ename varchar(100)
Step3: Take total rows count from temp table
SELECT #ROWNUMBER = COUNT(*) FROM #tmp_sri
declare #rno int
Step4: Loop temp table based on unique row number create in temp
while #rownumber>0
begin
set #rno=#rownumber
select #ename=ename from #tmp_sri where rno=#rno **// You can take columns data from here as many as you want**
set #rownumber=#rownumber-1
print #ename **// instead of printing, you can write insert, update, delete statements**
end
This approach only requires one variable and does not delete any rows from #databases. I know there are a lot of answers here, but I don't see one that uses MIN to get your next ID like this.
DECLARE #databases TABLE
(
DatabaseID int,
Name varchar(15),
Server varchar(15)
)
-- insert a bunch rows into #databases
DECLARE #CurrID INT
SELECT #CurrID = MIN(DatabaseID)
FROM #databases
WHILE #CurrID IS NOT NULL
BEGIN
-- Do stuff for #CurrID
SELECT #CurrID = MIN(DatabaseID)
FROM #databases
WHERE DatabaseID > #CurrID
END
Here's my solution, which makes use of an infinite loop, the BREAK statement, and the ##ROWCOUNT function. No cursors or temporary table are necessary, and I only need to write one query to get the next row in the #databases table:
declare #databases table
(
DatabaseID int,
[Name] varchar(15),
[Server] varchar(15)
);
-- Populate the [#databases] table with test data.
insert into #databases (DatabaseID, [Name], [Server])
select X.DatabaseID, X.[Name], X.[Server]
from (values
(1, 'Roger', 'ServerA'),
(5, 'Suzy', 'ServerB'),
(8675309, 'Jenny', 'TommyTutone')
) X (DatabaseID, [Name], [Server])
-- Create an infinite loop & ensure that a break condition is reached in the loop code.
declare #databaseId int;
while (1=1)
begin
-- Get the next database ID.
select top(1) #databaseId = DatabaseId
from #databases
where DatabaseId > isnull(#databaseId, 0);
-- If no rows were found by the preceding SQL query, you're done; exit the WHILE loop.
if (##ROWCOUNT = 0) break;
-- Otherwise, do whatever you need to do with the current [#databases] table row here.
print 'Processing #databaseId #' + cast(#databaseId as varchar(50));
end
This is the code that I am using 2008 R2. This code that I am using is to build indexes on key fields (SSNO & EMPR_NO) n all tales
if object_ID('tempdb..#a')is not NULL drop table #a
select 'IF EXISTS (SELECT name FROM sysindexes WHERE name ='+CHAR(39)+''+'IDX_'+COLUMN_NAME+'_'+SUBSTRING(table_name,5,len(table_name)-3)+char(39)+')'
+' begin DROP INDEX [IDX_'+COLUMN_NAME+'_'+SUBSTRING(table_name,5,len(table_name)-3)+'] ON '+table_schema+'.'+table_name+' END Create index IDX_'+COLUMN_NAME+'_'+SUBSTRING(table_name,5,len(table_name)-3)+ ' on '+ table_schema+'.'+table_name+' ('+COLUMN_NAME+') ' 'Field'
,ROW_NUMBER() over (order by table_NAMe) as 'ROWNMBR'
into #a
from INFORMATION_SCHEMA.COLUMNS
where (COLUMN_NAME like '%_SSNO_%' or COLUMN_NAME like'%_EMPR_NO_')
and TABLE_SCHEMA='dbo'
declare #loopcntr int
declare #ROW int
declare #String nvarchar(1000)
set #loopcntr=(select count(*) from #a)
set #ROW=1
while (#ROW <= #loopcntr)
begin
select top 1 #String=a.Field
from #A a
where a.ROWNMBR = #ROW
execute sp_executesql #String
set #ROW = #ROW + 1
end
SELECT #pk = #pk + 1
would be better:
SET #pk += #pk
Avoid using SELECT if you are not referencing tables are are just assigning values.

Resources