Procedure Syntax isn't correct - tsql

I'm not new to PL/SQL or Procedure programming in an MSSQL database (2012). But I am rusty and I'm messing up the syntax.
CREATE PROCEDURE [dbo].[AddActivity]
#activity_name nvarchar(255),
#responsible_first_name nvarchar(255),
#responsible_last_name nvarchar(255),
#estimated_savings numeric(18),
#estimated_start datetime,
#estimated_end datetime,
#department_id int,
#description nvarchar(MAX)
AS
DECLARE #return_code AS int = 0;
IF NOT EXISTS(SELECT 1 FROM dbo.Department WHERE #department_id = id)
BEGIN
#return_code = -1
END
ELSE
IF NOT EXISTS(SELECT 1 FROM dbo.Activity WHERE #activity_name = activity_name)
BEGIN
/* There is no duplicate (supposedly) so insert the entry here. */
END
ELSE
BEGIN
#return_code = -2
END
RETURN #return_code
Help out a fellow developer and his rusty memory? :D

At least one problem is#return_code = -1. You need either SET or SELECT:
SELECT #return_code = -1

You need to SET the value in your variable(#return_code) which you have DECLARE. Try this:
CREATE PROCEDURE [dbo].[AddActivity]
#activity_name nvarchar(255),
#responsible_first_name nvarchar(255),
#responsible_last_name nvarchar(255),
#estimated_savings numeric(18),
#estimated_start datetime,
#estimated_end datetime,
#department_id int,
#description nvarchar(MAX)
AS
DECLARE #return_code AS int = 0;
IF NOT EXISTS(SELECT 1 FROM dbo.Department WHERE #department_id = id)
BEGIN
SET #return_code = -1
END
ELSE
IF EXISTS(SELECT 1 FROM dbo.Activity WHERE #activity_name = activity_name)
BEGIN
SET #return_code = -2 --Removed the empty BEGIN/END by changing the IF NOT EXISTS to IF EXISTS
END
RETURN #return_code

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

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

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