I have written Procedure based on condition assign value - sql-server

CREATE PROC Valtest( #job_id INT)
AS
BEGIN
DECLARE #count INT
DECLARE #response VARCHAR(50)
SELECT #count=Count(0)
FROM employee
WHERE job_id=#job_id
IF(#count = 0 )
SET #response='No';
ELSE
SET #response='Yes';
ENDDECLARE #response VARCHAR(50)`enter code here`EXEC #response
=Valtest 5SELECT #response
--exec test 200

Proper way:
CREATE PROC Valtest( #job_id INT)
AS
BEGIN
IF EXISTS(SELECT 1 FROM employee WHERE job_id=#job_id)
SELECT 'Yes';
ELSE
SELECT 'No';
END
Return statement from stored procedure indicates the status - 0 procedure was run successfully. If you need to return value you should use OUTPUT parameter;
CREATE PROC Valtest( #job_id INT, #result VARCHAR(100) OUTPUT)
AS
BEGIN
IF EXISTS(SELECT 1 FROM employee WHERE job_id=#job_id)
SET #result = 'Yes';
ELSE
SET #result = 'No';
END;
DECLARE #r NVARCHAR(100);
EXEC Valtest #job_id = 200, #result = #r OUTPUT;
SELECT #r;

Related

How to bring multiple output values from a stored procedure from another server using dynamic sql

I'm working on a stored procedure that needs to call a procedure that is in another server using dynamic SQL. But I need to get the two output values and a return value if some condition is met. This is an example code:
CREATE PROCEDURE [MYPROCEDURE](
#PARAM1 INT,
#PARAM2 NVARCHAR(250),
#PARAM3 INT,
#SERVER_NAME NVARCHAR(MAX))
AS
BEGIN
DECLARE #SQLQUERY NVARCHAR(MAX)
SET #SQLQUERY = 'EXEC ' + #SERVER_NAME + '.[dbo].[DB].[OTHERPROCEDURE] #PARAM1,#PARAM2,#PARAM3'
EXEC (#SQLQUERY)
END
This is how the "OTHERPROCEDURE" would look like
CREATE PROCEDURE [OTHERPROCEDURE](
#PARAM1 INT,
#PARAM2 NVARCHAR(250) OUTPUT,
#PARAM3 INT OUTPUT,
AS
BEGIN
--DO SOMETHING
IF SOME_CONDITION_IS_MET
BEGIN
--DO THIS
RETURN SOME_VALUE
END
ELSE IF SOME_OTHER_CONDITION
BEGIN
--DO THIS
RETURN SOME_VALUE
END
ELSE
BEGIN
--DO THIS, DON'T RETURN ANY VALUE
END
--FINISH DOING SOMETHING WITH PARAMS
--DON'T RETURN ANY VALUE
END
Thanks in advance.
This doesn't actually need dynamic SQL at all, as the procedure name for EXEC can be parameterized
CREATE PROCEDURE [MYPROCEDURE] #Param1 int,
#Param2 nvarchar(250) OUTPUT,
#Param3 int OUTPUT,
#ServerName sysname
AS
DECLARE #procName nvarchar(1100) = QUOTENAME(#ServerName) + N'.[dbo].[DB].[OTHERPROCEDURE]';
EXEC #Return = #procName
#PARAM1 = #PARAM1,
#PARAM2 = #PARAM2 OUTPUT,
#PARAM3 = #PARAM3 OUTPUT;
RETURN #Return;
go
Assuming by RETURN in the definition of OTHERPROCEDURE you do mean RETURN, then use a parametrised dynamic statement:
CREATE PROCEDURE [MYPROCEDURE] #Param1 int,
#Param2 nvarchar(250),
#Param3 int,
#ServerName sysname
AS
BEGIN
DECLARE #SQL nvarchar(MAX);
SET #SQL = (SELECT N'EXEC #Return = ' + QUOTENAME(s.name) + N'.[dbo].[DB].[OTHERPROCEDURE] #PARAM1,#PARAM2,#PARAM3;'
FROM sys.servers s
WHERE s.[name] = #ServerName)
DECLARE #Return int;
EXEC sys.sp_executesql #SQL, N'#Param1 int, #Param2 nvarchar(250),#Param3 int,#Return int OUTPUT', #Param1, #Param2, #Param3, #Return OUTPUT;
RETURN #Return;
END;

Get value from store or store and get if not exists

what I want to achieve is a way to get previously generated or generate, store and return data, in a way, which could be used as function - needed to join or APPLY in UPDATE scripts.
So, having data generate function:
ALTER FUNCTION generateData()
RETURNS NVARCHAR(20)
AS
BEGIN
RETURN 'asdyukyuk' --some rng related algorithm
END
And "get or generate, save and get" procedure:
ALTER PROCEDURE getOrGenerateAndGet (#orig NVARCHAR(20), #result NVARCHAR(20) OUTPUT)
AS
BEGIN
IF #orig IS NULL
BEGIN
SET #result = NULL
END
ELSE
BEGIN
DECLARE #hash VARBINARY(64) = dbo.getHash(#orig)
SELECT #result = GENERATED_DATA FROM STORED_DATA WHERE HASH = #hash
IF #result IS NULL
BEGIN
SET #result = dbo.generateData()
INSERT INTO STORED_DATA (HASH, GENERATED_DATA) VALUES (#hash, #result)
END
END
RETURN 1
END;
GO
And UPDATE script:
UPDATE FRAGILE_DATA SET FRAGILE_COLUMN = getOrGenerateAndGet(FRAGILE_COLUMN)
it's obviously not working, because getOrGenerateAndGet is not function.
However, with function way:
CREATE FUNCTION getOrGenerateAndGet (#orig NVARCHAR(20))
RETURNS NVARCHAR(20)
AS
BEGIN
DECLARE #result NVARCHAR(20)
IF #orig IS NULL
BEGIN
SET #result = NULL
END
ELSE
BEGIN
DECLARE #hash VARBINARY(64) = dbo.getHash(#orig)
SELECT #result = GENERATED_DATA FROM STORED_DATA WHERE HASH = #hash
IF #result IS NULL
BEGIN
SELECT #result = dbo.generateData()
EXEC sp_executesql N'INSERT INTO STORED_DATA (HASH, GENERATED_DATA) VALUES (#hash, #result)'
END
END
RETURN #result
END;
GO
it's still not working, because "Only functions and some extended stored procedures can be executed from within a function."
Is there any way to achieve this, without enabling sql command shell?

Getting an output from a stored procedure

I have created this stored procedure
CREATE PROCEDURE AddNewMaterialType4
(#category varchar(15),
#materialType varchar(50),
#userID varchar(15),
#result1 varchar(15) OUTPUT)
AS
DECLARE #count1 INT;
SET #count1 = 0;
SELECT #count1 = COUNT(*)
FROM [vmsMaterialType]
WHERE category = #category
AND materialType = #materialType;
IF #count1 = 0
BEGIN
SET NOCOUNT ON;
INSERT INTO [vmsMaterialType] ([category], [materialType],[createdBy])
VALUES (#category, #materialType, #userID);
SET #result1 = 'Success';
END
ELSE
SET #result1 = 'Fail';
GO
When I execute the following I am not getting the result I expect (Success/Fail) instead its giving me the output what ever I declare result1 as.
declare
#result1 varchar(15) = '1';
begin
execute AddNewMaterialType4 #category = 'Beef', #materialtYPE = '25 Trim', #userID = 'JJ', #result1 = #result1;
print #result1;
end;
In your execute AddNewMaterialType4 call, you have to explicitly state that #result1 is an output variable. Try this instead:
declare
#result1 varchar(15) = '1';
begin
execute AddNewMaterialType4 #category = 'Beef', #materialtYPE = '25 Trim', #userID = 'JJ', #result1 = #result1 output;
print #result1;
end;

insert collection of data into sql server columns with storedprocedure

i'm begginer in sql server
i want to insert collection of data into the column in stored procedure
i want pass data from c# like this (100,'3,5,4,2,9') and insert to the column like this
ID Number
100 3
100 5
100 4
100 2
100 9
My procedure code
ALTER PROCEDURE [dbo].[Number]
#Number CHAR(10),
AS
BEGIN
BEGIN TRY
INSERT INTO NumbersTbl
VALUES(#Number)
SELECT 1
END TRY
BEGIN CATCH
EXEC SQLError
SELECT -1
END CATCH
END
how i can do it?
thank you
Procedure Definition
ALTER PROCEDURE [dbo].[Number]
#Value INT,
#Number Varchar(100),
#Sucecc BIT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #xml xml;
BEGIN TRY
SET #xml = cast(('<X>'+replace(#Number,',' ,'</X><X>')+'</X>') as xml)
INSERT INTO NumbersTbl (Column1 , Column2)
SELECT #Value, N.value('.', 'varchar(100)') as value
FROM #xml.nodes('X') as T(N)
SET #Sucecc = 1;
END TRY
BEGIN CATCH
EXEC SQLError
SET #Sucecc = 0;
END CATCH
END
Call Procedure
DECLARE #Result BIT;
Exec [dbo].[Number] #Value = 100
,#Number = '3,5,4,2,9'
,#Sucecc = #Result OUTPUT
First you can create the special function to parse input numbers:
CREATE FUNCTION dbo.splitstring ( #stringToSplit VARCHAR(MAX) )
RETURNS
#returnList TABLE ([Numbers] [nvarchar] (500))
AS
BEGIN
DECLARE #name NVARCHAR(255)
DECLARE #pos INT
WHILE CHARINDEX(',', #stringToSplit) > 0
BEGIN
SELECT #pos = CHARINDEX(',', #stringToSplit)
SELECT #name = SUBSTRING(#stringToSplit, 1, #pos-1)
INSERT INTO #returnList
SELECT #name
SELECT #stringToSplit = SUBSTRING(#stringToSplit, #pos+1, LEN(#stringToSplit)-#pos)
END
INSERT INTO #returnList
SELECT #stringToSplit
RETURN
END
And then edit your procedure:
ALTER PROCEDURE [dbo].[Number]
#ID INT,
#Number VARCHAR(MAX)
AS
BEGIN
BEGIN TRY
INSERT INTO NumbersTbl(ID, Number)
SELECT #ID, Numbers
FROM dbo.splitstring(#Number)
END TRY
BEGIN CATCH
EXEC SQLError
SELECT -1
END CATCH
END
Call: EXEC Number 100,'3,5,4,2,9'

How to pass output parameter to a Stored Procedure?

I have written a stored procedure with the following format:
ALTER PROCEDURE usp_data_migration
(#sourceDatabase varchar(50),
#sourceTable varchar(50),
#targetDatabase varchar(50),
#targetTable varchar(50),
#finaloutput varchar(max) output)
AS
BEGIN
----Set of SQL Blocks
END
Then, I am executing the procedure:
DECLARE #finaloutput1 varchar(300)
EXEC usp_data_migration 'Yousuf', 'emp', '[City Branch]', 'emp_tgt', #finaloutput1 output
SELECT #finaloutput1
By executing this way I don't proper output.
When I execute this way:
DECLARE #finaloutput1 varchar(300)
EXEC usp_data_migration #sourceDatabase = 'Yousuf',
#sourceTable = 'emp',
#targetDatabase = '[City Branch]',
#targetTable = 'emp_tgt',
#finaloutput1 output
SELECT #finaloutput1
I get an error message saying:
Msg 119, Level 15, State 1, Line 41
Must pass parameter number 5 and subsequent parameters as '#name = value'. After the form '#name = value' has been used, all subsequent parameters must be passed in the form '#name = value'.
And if I removed my output parameter and execute the procedure, I get my desired output but I am not able to get my result as an output.
EXEC usp_data_migration #sourceDatabase = 'Yousuf',
#sourceTable = 'emp',
#targetDatabase = '[City Branch]',
#targetTable = 'emp_tgt'
What should I do?
Thanks in advance.
The error message is self-explanatory - you should name all of your parameters.
DECLARE #finaloutput1 varchar(300);
EXEC dbo.usp_data_migration -- always use schema prefix
#sourceDatabase = 'Yousuf',
#sourceTable = 'emp',
#targetDatabase = '[City Branch]',
#targetTable = 'emp_tgt',
#finaloutput = #finaloutput1 OUTPUT;
SELECT #finaloutput1;
You have to Select like this
Example 1
create procedure p1
(
#id INT,
#name varchar(20) OUTPUT,
#company varchar(20) OUTPUT
)
AS
BEGIN
Set #name = 'name'
Set #company = 'company'
select #name , #company from table1 where id = #id;
END
GO
Example 2
CREATE PROCEDURE Myproc
#parm varchar(10),
#parm1OUT varchar(30) OUTPUT,
#parm2OUT varchar(30) OUTPUT
AS
SELECT #parm1OUT='parm 1' + #parm
SELECT #parm2OUT='parm 2' + #parm
GO
DECLARE #SQLString NVARCHAR(500)
DECLARE #ParmDefinition NVARCHAR(500)
DECLARE #parmIN VARCHAR(10)
DECLARE #parmRET1 VARCHAR(30)
DECLARE #parmRET2 VARCHAR(30)
SET #parmIN=' returned'
SET #SQLString=N'EXEC Myproc #parm,
#parm1OUT OUTPUT, #parm2OUT OUTPUT'
SET #ParmDefinition=N'#parm varchar(10),
#parm1OUT varchar(30) OUTPUT,
#parm2OUT varchar(30) OUTPUT'
EXECUTE sp_executesql
#SQLString,
#ParmDefinition,
#parm=#parmIN,
#parm1OUT=#parmRET1 OUTPUT,#parm2OUT=#parmRET2 OUTPUT
SELECT #parmRET1 AS "parameter 1", #parmRET2 AS "parameter 2"
go
drop procedure Myproc
Please refer more here
Simple Example:
create procedure proc2 #var int out,#var2 varchar(10) out
as
begin
set #var=(select max(id) from customer);
set #var2=(select name from customer where id=#var);
end
declare #maxid int;
declare #maxname varchar(10);
exec proc2 #maxid out,#maxname out;
select #maxid,#maxname;

Resources