Assign a list of integers to an #var - tsql

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));

Related

set multiple value with comma in single variable select data from table

set multiple value with comma in single variable select data from table
DECLARE #Values varchar(1000)
SET #Values = 'A, B, C'
SELECT
blah
FROM
foo
blah value like A, B, C, D, E..
DECLARE #Crossing1_Table TABLE (Crossing_No NVARCHAR(200), userid INT, GameName varchar(50),
GameDate date, CrossingQty INT, ccount int)
DECLARE #Id int
DECLARE #cross1 varchar(MAX)
DECLARE #ganame varchar(50)
DECLARE #gdate date
DECLARE #Cqty int
DECLARE cur_emp CURSOR
STATIC FOR
SELECT CrossingValue1, UserId, GameName, TodayDate, CrossingQty
FROM Game where GameListId=#Gamename and Cast(TodayDate as DATE)=#Gamedate
OPEN cur_emp
IF ##CURSOR_ROWS > 0
BEGIN
FETCH NEXT FROM cur_emp INTO #cross1, #Id, #ganame, #gdate, #Cqty
WHILE ##Fetch_status = 0
BEGIN
INSERT INTO #Crossing1_Table
SELECT CAST(Item AS INT), #Id, #ganame, #gdate, #Cqty, 1
FROM dbo.SplitString(#cross1, ',')
FETCH NEXT FROM cur_emp INTO #cross1, #Id, #ganame, #gdate, #Cqty
END
END
CLOSE cur_emp
DEALLOCATE cur_emp

SQL Server 2012: check if is uniqueidentifier and convert to string

I am trying to test if a variable is a uniqueidentifier and if it is then convert it to string but it fails:
Declare #Item VARCHAR(50)
Declare #OutString varchar(max) ;
--#Outstring is populated from various tables each cell separated by ','
--Getting the #Item from the #Outstring and convert it if its uid
DECLARE #Pos INT
DECLARE #Loop BIT
SELECT #Loop = CASE WHEN LEN(#OutString) > 0 THEN 1 ELSE 0 END
WHILE (SELECT #Loop) = 1
BEGIN
SELECT #Pos = CHARINDEX(',', #OutString, 1)
IF #Pos > 0
BEGIN
SELECT #Item = SUBSTRING(#OutString, 1, #Pos - 1)
SELECT #OutString = SUBSTRING(#OutString, #Pos + 1, LEN(#OutString) - #Pos)
IF (TRY_CONVERT(UNIQUEIDENTIFIER, #Item) IS NOT NULL)
BEGIN
CONVERT(NVARCHAR(50), #Item) AS #Item --ERROR LINE incorrect syntax
END
END
END
it is either
select #Item = convert(nvarchar(50), #Item)
or
select #Item = cast(#Item as nvarchar(50))
The syntax error is because you have said the action but not what SQL should do with it.
Do you want the string to be returned?
SELECT CONVERT(NVARCHAR(50), #Item) AS Item
Appended to #Item? (but this variable is inside your loop?)
SET #Item += CONVERT(NVARCHAR(50), #Item)
Not sure what you want to do once you have converted the string. Maybe you need another variable to add the string on (like above except not SET #Item)
Use
SELECT convert(nvarchar(50), #Item ) as Item

Stored procedure returns nullable int

In my procedure i am returning a int value.
ALTER PROCEDURE [dbo].[GetValue]
-- Add the parameters for the stored procedure here
#ID int,
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
DECLARE #isNew int
SET #isNew=0
DECLARE #returnedValue int
DECLARE #output int
SET #returnedValue=[dbo].fn_GetIsNewLecturer(#ID)
IF(#returnedValue=0)
BEGIN
PRINT 'new'
EXEC #output=[dbo].[GetNew] #ID
SELECT #output
END
ELSE
BEGIN
PRINT 'old'
EXEC #output=[dbo].[sp_GetOld] #ID
SELECT #output
END
RETURN #output
END
it return value should be int. But it returns Nullable int?. how to change it as int
Try this:
select [Output] = isnull(#output, 0)
Here's why it should work:
declare #i int
select ni = #i, nni = isnull(#i,0)
into #t
select is_nullable, *
from tempdb.sys.columns
where [object_id] = object_id(N'tempdb..#t')
drop table #t

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

How does one use loops in 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