How does one use loops in TSQL? - tsql

In TSQL, I would like to change the following code from have to use hard coded dhomes to using a loop for optimization. My failed attempt at trying to add a loop is also included.
Declare #dhome Tinyint, #bp smallint, #lr smallint, #q smallint
// Set #dhome = 1
While(#dhome <= 3) // My attempt to add a loop
SELECT #lr = MAX(NQdDate), #q = NQd
FROM NQdHistory
WHERE dhomeId = #dhome
GROUP BY NQdDate, NQd
SELECT #bd = COUNT(*)
FROM bdhome
WHERE NQdDate= #lr AND dhomeID= #dhome
DELETE FROM ND1 WITH(XLOCK)
WHERE dhomeID= #dhome AND NQdDate= #lr
UPDATE NQdHistory
SET Nbd = #q - ##RowCount - #bp, NBd = #bp
WHERE NQdDate= #lr AND dhomeID= #dhome
Set #dhome = #dhome +1 //My attempt to end a loop

You're on the right track. You're missing your begin and end. Also, be sure to give #dhome a value. It looks like you started to and have it commented out on your third line:
Declare #dhome Tinyint, #bp smallint, #lr smallint, #q smallint
// Set #dhome = 1
While(#dhome <= 3) // My attempt to add a loop
begin
SELECT #lr = MAX(NQdDate), #q = NQd
FROM NQdHistory
WHERE dhomeId = #dhome
GROUP BY NQdDate, NQd
SELECT #bd = COUNT(*)
FROM bdhome
WHERE NQdDate= #lr AND dhomeID= #dhome
DELETE FROM ND1 WITH(XLOCK)
WHERE dhomeID= #dhome AND NQdDate= #lr
UPDATE NQdHistory
SET Nbd = #q - ##RowCount - #bp, NBd = #bp
WHERE NQdDate= #lr AND dhomeID= #dhome
Set #dhome = #dhome +1 //My attempt to end a loop
end
If you're familiar with C/C#/C++, think of T-SQL's Begin and End like curly braces { and }, if you're more familiar with VB Then and End If. Or more like pascals Begin and End. You get the idea :)

Missing a begin and end on your while.
WHILE (Transact-SQL)

Example 1
DECLARE #I INT,#COUNTVAR INT
SET #I = 1
DECLARE #Parent_Child TABLE(ID INT IDENTITY(1,1),ParentPositionID INT NULL,ChildPositionId Int)
INSERT INTO #Parent_Child(ParentPositionID,ChildPositionId)
SELECT DISTINCT PARENT_POSITION_ID,CHILD_POSITION_ID from tblPOSITION_HIERARCHY
--WHERE CHILD_POSITION_ID IN (--YOUR CONDITION IF ANY)
SELECT #COUNTVAR =COUNT(*) FROM #PTS_Parent_Child
DECLARE #int_SUPE_POSITION_ID INT, #int_CHILD_POSITION_ID INT
--loop through records here
WHILE #I <= #COUNTVAR
BEGIN
SELECT #int_SUPE_POSITION_ID=ParentPositionID,#int_CHILD_POSITION_ID=ChildPositionId FROM #Parent_Child WHERE ID=#I
--Whatever you want to do with records
SET #I=#I+1
END
Example 2
Just another approach if you are fine using temp tables.I have personally tested this and it will not cause any exception (even if temp table does not have any data.)
CREATE TABLE #TempTable
(
ROWID int identity(1,1) primary key,
HIERARCHY_ID_TO_UPDATE int,
)
--INSERT DATA INTO TEMP TABLE USING INSERT INTO CLAUSE OR FOR EAXMPLE BELOW
--INSERT INTO #TempTable VALUES(1)
--INSERT INTO #TempTable VALUES(2)
--INSERT INTO #TempTable VALUES(4)
--INSERT INTO #TempTable VALUES(6)
--INSERT INTO ##TempTable VALUES(8)
DECLARE #MAXID INT
SET #COUNTER =1
SELECT #MAXID=COUNT(*) FROM #TempTable
--PRINT #MAXID
WHILE (#MAXID > 0)
BEGIN
--DO THE PROCESSING HERE
SELECT #HIERARCHY_ID_TO_UPDATE =PT.HIERARCHY_ID_TO_UPDATE FROM #TempTable PT WHERE ROWID=#COUNTER
--PRINT '#MAXID VALUE '
--PRINT #MAXID
SET #MAXID=#MAXID-1
SET #COUNTER =#COUNTER + 1
End
If(OBJECT_ID('tempdb..#TempTable') IS NOT NULL)
BEGIN
DROP TABLE #TempTable
END

Related

TSQL - How to iterate a list of strings

I want to create a procedure that will insert all my jobs to the DB.
(a. All my jobs have equal characteristics. b. SSDT doesn't support jobs code management)
Now, I thought to create a script to insert all of them and as a c# developer I thought I need to initialize a list with their names.
I discovered while googling that the way to do it is with an in memory table and the best I could come with is this.
declare #jobsNames table(Id int, JobName nvarchar(100))
insert into #jobsNames (Id,JobName)
select 1,'JobName1' union
select 2,'JobName2' union
......
BEGIN TRANSACTION
DECLARE JobsCursor CURSOR FOR SELECT JobName FROM #jobsNames
OPEN JobsCursor
FETCH NEXT FROM JobsCursor INTO #JobName
WHILE ##Fetch_status = 0
BEGIN
.. do stuff
FETCH NEXT FROM JobsCursor INTO #JobName
WHILE ##Fetch_status = 0
END
COMMIT TRANSACTION
Question -
Is this the shortest/recommended way?
(It seems a hellotof code for a foreach)
declare #jobNames table(Id int, JobName nvarchar(100))
insert #jobNames values
(1, 'JobName1'),
(2, 'JobName2'),
--
(10, 'JobName10')
while exists(select 1 from #jobNames)
begin
declare #id int, #name nvarchar(100)
select top 1 #id = Id, #name = JobName from #jobNames
delete from #jobNames where Id = #Id
-- Do stuff here
end
Personally I avoid Cursors like the plague. Please make sure that you HAVE to iterate instead of doing your work set based. They don't call it RBAR for nothing.
DECLARE #counter INT, #max INT
SELECT #counter = 1, #max = max(id)
FROM #jobsNames
WHILE #counter <= #max
BEGIN
SELECT #val1 = val1 ... FROM #jobNames where ID = #counter
-- .. do stuff
SET #counter = #counter + 1
END

trigger only fired one when i use insert into select

CREATE TRIGGER tg_bpb_cons_no ON dbo.t_bpb_cons
FOR INSERT
AS
/*
fungsi : membuat document bon permintaan barang maintenance number secara otomatis`
author : ryan
*/
declare #new_doc_no varchar(20)
declare #doc_no varchar(20)
--declare #doc_no bigint
--update doc no
SELECT #doc_no = max(cast(substring(doc_no,9,13) as integer)) from t_bpb_cons
IF (#doc_no IS NULL)
BEGIN
set #doc_no = 0
END
PRINT #DOC_NO
SELECT #new_doc_no = cast(#doc_no+1 as varchar(20))
SELECT #new_doc_no = LEFT('BPB/CON/',8+len(#new_doc_no))+#new_doc_no
UPDATE t_bpb_cons SET doc_no=#new_doc_no WHERE [ID]=(SELECT MAX([ID]) AS id from t_bpb_cons)
it works fine with single record inserted, but i used Insert into tbl select tblvalue from AnotherTable to insert multiple record it's only affected on the last record...
why ??
Insert statement (even having multiple rows) treated as a single operation, you have to handle by yourself the inserted values in the trigger code.
try this :
CREATE TRIGGER tg_bpb_cons_no ON dbo.t_bpb_cons
FOR INSERT
AS
/*
fungsi : membuat document bon permintaan barang maintenance number secara otomatis`
author : ryan
*/
declare #new_doc_no varchar(20)
declare #doc_no int
declare #row_inserted int
select #row_inserted = count(*) from inserted
--declare #doc_no bigint
--update doc no
SELECT #doc_no = max(cast(substring(doc_no,9,13) as integer)) from t_bpb_cons
IF (#doc_no IS NULL)
BEGIN
set #doc_no = 0
END
WHILE #doc_no < #doc_no + #row_inserted
BEGIN
PRINT #DOC_NO
SELECT #new_doc_no = cast(#doc_no+1 as varchar(20))
SELECT #new_doc_no = LEFT('BPB/CON/',8+len(#new_doc_no))+#new_doc_no
UPDATE t_bpb_cons SET doc_no=#new_doc_no WHERE [ID] = (SELECT MAX([ID]) AS id from inserted)
SET #doc_no = #doc_no + 1
END

Dynamic SQL and Functions

is there any way of accomplishing something like the following:
CREATE FUNCTION GetQtyFromID
(
#oricod varchar(15),
#ccocod varchar(15),
#ocmnum int,
#oinnum int,
#acmnum int,
#acttip char(2),
#unisim varchar(15)
)
AS
RETURNS DECIMAL(18,8)
BEGIN
DECLARE #Result decimal(18,8)
DECLARE #SQLString nvarchar(max);
DECLARE #ParmDefinition nvarchar(max);
--I need to execute a query stored in a cell which returns the calculated qty.
--i.e of AcuQry: select #cant = sum(smt) from table where oricod = #oricod and ...
SELECT #SQLString = AcuQry
FROM OinActUni
WHERE (OriCod = #oricod) AND (ActTipCod = #acttip) AND (UniSim = #unisim) AND (AcuEst > 0)
SET #ParmDefinition = N'
#oricod varchar(15),
#ccocod varchar(15),
#ocmnum int,
#oinnum int,
#acmnum int,
#cant decimal(18,8) output';
EXECUTE sp_executesql #SQLString, #ParmDefinition,
#oricod = #oricod,
#ccocod = #ccocod,
#ocmnum = #ocmnum,
#oinnum = #oinnum,
#acmnum = #acmnum,
#cant = #result OUTPUT;
RETURN #Result
END
The problem with this approach is that it is prohibited to execute sp_excutesql in a function...
What I need is to do something like:
select id, getQtyFromID(id) as qty
from table
The main idea is to execute a query stored in a table cell, this is because the qty of something depends on it's unit. the unit can be days or it can be metric tons, so there is no relation between the units, therefore the need of a specific query for each unit.
What about using an if then or case expression in a stored procedure to check the unit, then perform specific calculations based on the type of unit?

Assign a list of integers to an #var

I can:
declare #idOrder int
set #idOrder = 21319
I want:
declare #idOrder int
set #idOrder = (21319, 21320)
for use in a series of statements where the 'WHERE' clause uses the IN operator
delete Orders
where idOrder in #idOrder
instead of
delete Orders
where idOrder in (21319, 21320)
You can't do that as long as it's an int, as that's not a valid value for that datatype. A datatype that could take several integers is a table
declare #idOrder table (id int)
insert into #idOrder values(21319)
insert into #idOrder values(21320)
delete from Orders where idOrder in (select id from #idOrder)
In SQL Server you can also
CREATE FUNCTION [dbo].[fn_ado_param_int] (#ado nvarchar(4000))
RETURNS #VALUES TABLE (ado int)AS
BEGIN
declare #Delim char(1)
set #Delim = ','
DECLARE #chrind INT
DECLARE #Piece nvarchar(4000)
SELECT #chrind = 1
WHILE #chrind > 0
BEGIN
SELECT #chrind = CHARINDEX(#Delim,#ado)
IF #chrind > 0
SELECT #Piece = LEFT(#ado,#chrind - 1)
ELSE
SELECT #Piece = #ado
INSERT #VALUES(ado) VALUES(#Piece)
SELECT #ado = RIGHT(#ado,LEN(#ado) - #chrind)
IF LEN(#ado) = 0 BREAK
END
RETURN
END
declare #idOrder varchar(500);
set #inOrder = "21319,2138,2138";
delete from Orders where id in (select ado from dbo.fn_ado_param_int(#idOrder));

How to get sp_executesql result into a variable?

I have a piece of dynamic SQL I need to execute, I then need to store the result into a variable.
I know I can use sp_executesql but can't find clear examples around about how to do this.
If you have OUTPUT parameters you can do
DECLARE #retval int
DECLARE #sSQL nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
DECLARE #tablename nvarchar(50)
SELECT #tablename = N'products'
SELECT #sSQL = N'SELECT #retvalOUT = MAX(ID) FROM ' + #tablename;
SET #ParmDefinition = N'#retvalOUT int OUTPUT';
EXEC sp_executesql #sSQL, #ParmDefinition, #retvalOUT=#retval OUTPUT;
SELECT #retval;
But if you don't, and can not modify the SP:
-- Assuming that your SP return 1 value
create table #temptable (ID int null)
insert into #temptable exec mysp 'Value1', 'Value2'
select * from #temptable
Not pretty, but works.
DECLARE #vi INT
DECLARE #vQuery NVARCHAR(1000)
SET #vQuery = N'SELECT #vi= COUNT(*) FROM <TableName>'
EXEC SP_EXECUTESQL
#Query = #vQuery
, #Params = N'#vi INT OUTPUT'
, #vi = #vi OUTPUT
SELECT #vi
DECLARE #tab AS TABLE (col1 VARCHAR(10), col2 varchar(10))
INSERT into #tab EXECUTE sp_executesql N'
SELECT 1 AS col1, 2 AS col2
UNION ALL
SELECT 1 AS col1, 2 AS col2
UNION ALL
SELECT 1 AS col1, 2 AS col2'
SELECT * FROM #tab
Return values are generally not used to "return" a result but to return success (0) or an error number (1-65K). The above all seem to indicate that sp_executesql does not return a value, which is not correct. sp_executesql will return 0 for success and any other number for failure.
In the below, #i will return 2727
DECLARE #s NVARCHAR(500)
DECLARE #i INT;
SET #s = 'USE [Blah]; UPDATE STATISTICS [dbo].[TableName] [NonExistantStatisticsName];';
EXEC #i = sys.sp_executesql #s
SELECT #i AS 'Blah'
SSMS will show this
Msg 2727, Level 11, State 1, Line 1
Cannot find index 'NonExistantStaticsName'.
If you want to return more than 1 value use this:
DECLARE #sqlstatement2 NVARCHAR(MAX);
DECLARE #retText NVARCHAR(MAX);
DECLARE #ParmDefinition NVARCHAR(MAX);
DECLARE #retIndex INT = 0;
SELECT #sqlstatement = 'SELECT #retIndexOUT=column1 #retTextOUT=column2 FROM XXX WHERE bla bla';
SET #ParmDefinition = N'#retIndexOUT INT OUTPUT, #retTextOUT NVARCHAR(MAX) OUTPUT';
exec sp_executesql #sqlstatement, #ParmDefinition, #retIndexOUT=#retIndex OUTPUT, #retTextOUT=#retText OUTPUT;
returned values are in #retIndex and #retText
Declare #variable int
Exec #variable = proc_name
DECLARE #ValueTable TABLE
(
Value VARCHAR (100)
)
SELECT #sql = N'SELECT SRS_SizeSetDetails.'+#COLUMN_NAME+' FROM SRS_SizeSetDetails WHERE FSizeID = '''+#FSizeID+''' AND SRS_SizeSetID = '''+#SRS_SizeSetID+'''';
INSERT INTO #ValueTable
EXEC sp_executesql #sql;
SET #Value='';
SET #Value = (SELECT TOP 1 Value FROM #ValueTable)
DELETE FROM #ValueTable
This worked for me:
DECLARE #SQL NVARCHAR(4000)
DECLARE #tbl Table (
Id int,
Account varchar(50),
Amount int
)
-- Lots of code to Create my dynamic sql statement
insert into #tbl EXEC sp_executesql #SQL
select * from #tbl
Here's something you can try
DECLARE #SqlStatement NVARCHAR(MAX) = ''
,#result XML
,#DatabaseName VARCHAR(100)
,#SchemaName VARCHAR(10)
,#ObjectName VARCHAR(200);
SELECT #DatabaseName = 'some database'
,#SchemaName = 'some schema'
,#ObjectName = 'some object (Table/View)'
SET #SqlStatement = '
SELECT #result = CONVERT(XML,
STUFF( ( SELECT *
FROM
(
SELECT TOP(100)
*
FROM ' + QUOTENAME(#DatabaseName) +'.'+ QUOTENAME(#SchemaName) +'.' + QUOTENAME(#ObjectName) + '
) AS A1
FOR XML PATH(''row''), ELEMENTS, ROOT(''recordset'')
), 1, 0, '''')
)
';
EXEC sp_executesql #SqlStatement,N'#result XML OUTPUT', #result = #result OUTPUT;
SELECT DISTINCT
QUOTENAME(r.value('fn:local-name(.)', 'VARCHAR(200)')) AS ColumnName
FROM #result.nodes('//recordset/*/*') AS records(r)
ORDER BY ColumnName
This was a long time ago, so not sure if this is still needed, but you could use ##ROWCOUNT variable to see how many rows were affected with the previous sql statement.
This is helpful when for example you construct a dynamic Update statement and run it with exec. ##ROWCOUNT would show how many rows were updated.
Here is the definition