Dynamic SQL Not working - Complies , but errors out - sql-server

CREATE TABLE [dbo].[TSQL_DLOOKUP](
[LookUpTable] [nchar](10) NULL,
[LookUpField] [nchar](10) NULL,
[LookUpValue] [nchar](10) NULL,
[LookUpDecode] [nchar](20) NULL
) ON [PRIMARY]
GO
The procedure:
ALTER PROCEDURE [dbo].[MyDLookUp]
#LookUpValue NCHAR(10),
#LookUpTable NCHAR(10),
#LookUpField NCHAR(10)
AS
BEGIN
DECLARE #SQLQuery AS NVARCHAR(500)
DECLARE #ParameterDefinition AS NVARCHAR(100)
/* Build Transact-SQL String by including the parameter */
SET #SQLQuery = 'SELECT LookUpDecode FROM TSQL_DLOOKUP WHERE LookUpTable = #LookUpTable AND LookUpValue = #LookUpValue AND LookUpField =#LookUpField'
/* Execute Transact-SQL String */
EXECUTE sp_executesql #SQLQuery, #LookUpValue,#LookUpTable,#LookUpField
END
enter code here To run:
DECLARE #return_value int
EXEC #return_value = [dbo].[MyDLookUp]
#LookUpValue = N'F',
#LookUpTable = N'LCLASS',
#LookUpField = N'CLASS'
SELECT 'Return Value' = #return_value
The error: Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'F'.
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "#LookUpTable".
The code compiles, but will not run. Please help.
The idea here is to as accurately as possible replicate the MSACCESS DLOOOKUP function. I am on a project in which a lot of repeated SQL statements exist where the coder before me did it this way, I need to simplify things.

As said by LAMAK Clearly there is no need of Dynamic query here u can do the same by using staic query!!
SELECT lookupdecode
FROM tsql_dlookup
WHERE lookuptable = #LookUpTable
AND lookupvalue = #LookUpValue
AND lookupfield = #LookUpField
Function to do the same job
CREATE FUNCTION dlookup(#LookUpValue NCHAR(10),
#LookUpTable NCHAR(10),
#LookUpField NCHAR(10))
RETURNS nchar
AS
BEGIN
declare #lookupdecode nchar(50)
SELECT top 1 #lookupdecode = lookupdecode
FROM tsql_dlookup
WHERE lookuptable = #LookUpTable
AND lookupvalue = #LookUpValue
AND lookupfield = #LookUpField
RETURN #lookupdecode
END;

You are missing the #params parameter from the sp_executesql command which defines the parameters being passed in:
EXECUTE sp_executesql #SQLQuery,
N'#LookUpValue [nchar](10),#LookUpTable [nchar](10),#LookUpField [nchar](10)',
#LookUpValue,#LookUpTable,#LookUpField

As other said in this case there is no need of dynamic sql as it can be executed directly.
For answer to your question, see below.
The parameter definition needed to be passed as an argument to sp_executesql SP to pass parameters to a dynamic query http://msdn.microsoft.com/en-us/library/ms188001.aspx.
So, your new SP will be as follows
alter PROCEDURE [dbo].[MyDLookUp]
#LookUpValue NCHAR(10),
#LookUpTable NCHAR(10),
#LookUpField NCHAR(10)
AS
BEGIN
DECLARE #SQLQuery AS NVARCHAR(500)
DECLARE #ParameterDefinition AS NVARCHAR(100)
/* Build Transact-SQL String by including the parameter */
SET #SQLQuery = 'SELECT LookUpDecode FROM TSQL_DLOOKUP WHERE LookUpValue = #LookUpValue AND LookUpTable = #LookUpTable AND LookUpField =#LookUpField'
DECLARE #ParmDefinition nvarchar(500);
SET #ParmDefinition = N'#LookUpValue NCHAR(10), #LookUpTable NCHAR(10), #LookUpField NCHAR(10)';
/* Execute Transact-SQL String */
EXECUTE sp_executesql #SQLQuery, #ParmDefinition, #LookUpValue,#LookUpTable,#LookUpField
END

Try this Code, if this work for you because there is no need to use Dynamic SQL for simple select statment
---------------------------------------Stored Procedure
Alter PROCEDURE [dbo].[MyDLookUp] --[dbo].[MyDLookUp] 1,2,3
#LookUpValue NCHAR(10),
#LookUpTable NCHAR(10),
#LookUpField NCHAR(10)
AS
BEGIN
SELECT LookUpDecode FROM TSQL_DLOOKUP
WHERE LookUpTable = #LookUpTable AND LookUpValue = #LookUpValue AND LookUpField =#LookUpField
END

Related

T-SQL stuck on scope_identity return from stored procedure

I'm sure this is a easy fix, but I can't find an answer here. Been many a years since I have written stored procedures..
These are my procedures:
This first one works, and returns the newly created Id.
ALTER PROCEDURE [dbo].[sp_CreateBytegymType]
#Name NVARCHAR(200),
#Type NCHAR(1),
#Description NVARCHAR(MAX) NULL,
#Comment NVARCHAR(MAX) NULL,
#Source NVARCHAR(MAX) NULL,
#BtId INT OUTPUT
AS
BEGIN
SET NOCOUNT ON
INSERT INTO BytegymType
VALUES (#Name, #Type, #Description, #Comment, #Source)
SET #BtId = CAST(SCOPE_IDENTITY() AS INT)
END
The second one calls the first one:
ALTER PROCEDURE [dbo].[sp_CreateMuscle]
#Name NVARCHAR(200),
#Type NCHAR(1),
#Description NVARCHAR(MAX) NULL,
#Comment NVARCHAR(MAX) NULL,
#Source NVARCHAR(MAX) NULL,
#Group NVARCHAR(20) NULL
AS
BEGIN
DECLARE #BtId int
EXEC sp_CreateBytegymType
#Name = #Name,
#Type = #Type,
#Description = #Description,
#Comment = #Comment,
#Source = #Source,
#BtId = #BtId
INSERT INTO Muscle
VALUES (#BtId, #Group)
END
I get the following error:
Msg 515, Level 16, State 2, Procedure sp_CreateMuscle, Line 20 [Batch Start Line 2]
Cannot insert the value NULL into column 'BtId'
Seems I'm not keeping the #BtId value. Do I need to put it into a new value after executing the sp_CreateBytegymType?
Also I would like to do this in a transactional manner. So if the the insert into Muscle fails, it should rollback the stored procedure insert.
You need to add OUTPUT:
exec sp_CreateBytegymType
#Name = #Name,
#Type = #Type,
#Description = #Description,
#Comment = #Comment,
#Source = #Source,
#BtId = #BtId OUTPUT;
Also prefixing user defined stored procedures with sp_ is not advised. Related article: Is the sp_ prefix still a no-no?

Table Name from parameter in Stored Procedure

I'm trying to create a stored procedure. Here's a short version of my code:
CREATE PROCEDURE foobar
#table_name nvarchar(20),
#Work_Status nvarchar(20)
AS
BEGIN
update #table_name -- /// How Do I do this? ///
set work_status = #Work_Status
END
How can I define the table name via a parameter?
Try to use a dynamic query:
DECLARE #SQL NVARCHAR(4000)
DECLARE #ParamDefinition nvarchar(500)
SET #ParamDefinition = N'#Work_Status nvarchar(20), #day_no nvarchar(10), #day_month nvarchar(10), #day_years nvarchar(10)';
--...CURSOR declaration
--... BEGIN
SELECT #SQL =
N'update [SKTH_ENSUSER].[dbo].' + #tbl_name + '
set t_work_status = #Work_Status
where t_day_no = #day_no and t_month_no = #day_month and t_year_no = #day_years'
EXECUTE sp_executesql #SQL, #ParamDefinition, #Work_Status = #Work_Status, #day_no = #day_no, #day_month = #day_month, #day_years = #day_years
--...
-- FETCH NEXT FROM ENS_cursor
Updated: #SQL must be NVARCHAR

Nested sp_executesql not working with output variable

I am trying to call a stored procedure (with output variable) using sp_executesql but within another stored procedure. I wrote the following, but still not able to get trhough what that error means
This would be called from webservice code:
exec sp1 'obj1',#params
Here obj and params are of nvarchar(max)
Definition of sp1 is :
Alter procedure [dbo].[sp1 ]
#procname nvarchar(max),
#params nvarchar(max)
as
declare #temp varchar(15)
if #procname = 'obj1'
begin
set #params = #params + ',#Newval varchar(15) output'
EXEC sp_executesql #sp2,#params,#Newval=#temp OUTPUT
end
Definition of sp2:
Here I am returning #Newval
Error I am getting :
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near ','.
Also in 2 in place of exec statement , I have tried following:
EXEC sp_executesql #sp2, #params, #temp OUTPUT;
Results in the same error.
set #sql='sp2,' + ' #params ' + ',#params,#temp OUTPUT'
EXEC sp_executesql (#sql)
Also results in the same error.
I need this dynamic selection of stored procedures in sp1 and params is a nvarchar(max) string of parameters and their values, some of them are varchar and are embedded in ''value'' format but this string is fine as I am able to call the underlying sp2 with this.
Additional info, it it helps.
EXEC sp_executesql #sp2,#params,#Newval=#temp OUTPUT
in this #params is combination of keys and vlaue pairs for the final sp. something like :
'#key1="a",#key2="b"'
and so on, I can not predefined the #params but it is dynamic and it is working
fine when I run it with
exec (#sql)
Format while whole of the name, params are embedded in the #sql
If #params='' or NULL then your , before #Newval is irrelevant. I suggest you to check:
IF NULLIF(#params,'') IS NULL or #params IS NULL
SET #params = '#Newval varchar(15) output'
ELSE
SET #params = #params + ',#Newval varchar(15) output'
You are passing #sp2 maybe you need this:
ALTER PROCEDURE [dbo].[sp1]
#procname nvarchar(max),
#params nvarchar(max)
AS
DECLARE #temp varchar(15)
IF #procname = 'obj1'
BEGIN
SET #params = #params + ',#Newval varchar(15) output'
EXEC sp_executesql N'EXEC sp2 #someparam1, #someparam2, #Newval varchar(15) OUTPUT', #params, #someparam1 = 1, #someparam2 = 2, #Newval=#temp OUTPUT
END
EDIT
Working example:
USE [AdventureWorks]
GO
DECLARE #procname nvarchar(max) = 'EXEC [dbo].[uspGetWhereUsedProductID] #StartProductID, #CheckDate',
#params nvarchar(max) = '#StartProductID int, #CheckDate date'
EXEC sp_executesql #procname, #params, #StartProductID = 1, #CheckDate = '2015-10-17'
GO

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;

Execute stored procedure with an Output parameter?

I have a stored procedure that I am trying to test. I am trying to test it through SQL Management Studio. In order to run this test I enter ...
exec my_stored_procedure 'param1Value', 'param2Value'
The final parameter is an output parameter. However, I do not know how to test a stored procedure with output parameters.
How do I run a stored procedure with an output parameter?
The easy way is to right-click on the procedure in Sql Server Management Studio (SSMS), select 'Execute stored procedure..." and add values for the input parameters as prompted. SSMS will then generate the code to run the procedure in a new query window, and execute it for you. You can study the generated code to see how it is done.
you can do this :
declare #rowCount int
exec yourStoredProcedureName #outputparameterspOf = #rowCount output
Return val from procedure
ALTER PROCEDURE testme #input VARCHAR(10),
#output VARCHAR(20) output
AS
BEGIN
IF #input >= '1'
BEGIN
SET #output = 'i am back';
RETURN;
END
END
DECLARE #get VARCHAR(20);
EXEC testme
'1',
#get output
SELECT #get
Check this, where the first two parameters are input parameters and the 3rd is an Output parameter in the Procedure definition.
DECLARE #PK_Code INT;
EXEC USP_Validate_Login 'ID', 'PWD', #PK_Code OUTPUT
SELECT #PK_Code
Procedure Example :
Create Procedure [dbo].[test]
#Name varchar(100),
#ID int Output
As
Begin
SELECT #ID = UserID from tbl_UserMaster where Name = #Name
Return;
END
How to call this procedure
Declare #ID int
EXECUTE [dbo].[test] 'Abhishek',#ID OUTPUT
PRINT #ID
From https://learn.microsoft.com/en-US/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql (originally http://support.microsoft.com/kb/262499)
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
First, declare the output variable:
DECLARE #MyOutputParameter INT;
Then, execute the stored procedure, and you can do it without parameter's names, like this:
EXEC my_stored_procedure 'param1Value', #MyOutputParameter OUTPUT
or with parameter's names:
EXEC my_stored_procedure #param1 = 'param1Value', #myoutput = #MyOutputParameter OUTPUT
And finally, you can see the output result by doing a SELECT:
SELECT #MyOutputParameter
With this query you can execute any stored procedure (with or without an output parameter):
DECLARE #temp varchar(100)
EXEC my_sp
#parameter1 = 1,
#parameter2 = 2,
#parameter3 = #temp output,
#parameter4 = 3,
#parameter5 = 4
PRINT #temp
Here the datatype of #temp should be the same as #parameter3 within your Stored Procedure.
How about this? It's extremely simplified:
The SPROC below has an output parameter of #ParentProductID
We want to select the value of the output of #ParentProductID into #MyParentProductID which is declared below.
Here's the Code:
declare #MyParentProductID int
exec p_CheckSplitProduct #ProductId = 4077, #ParentProductID = #MyParentProductID output
select #MyParentProductID
Try this; it's working fine for the multiple output parameter:
CREATE PROCEDURE [endicia].[credentialLookup]
#accountNumber varchar(20),
#login varchar(20) output,
#password varchar(50) output
AS
BEGIN
SET NOCOUNT ON;
SELECT top 1 #login = [carrierLogin],#password = [carrierPassword]
FROM [carrier_account] where carrierLogin = #accountNumber
order by clientId, id
END
Try for the result:
SELECT *FROM [carrier_account]
DECLARE #login varchar(20),#password varchar(50)
exec [endicia].[credentialLookup] '588251',#login OUTPUT,#password OUTPUT
SELECT 'login'=#login,'password'=#password
CREATE PROCEDURE DBO.MY_STORED_PROCEDURE
(#PARAM1VALUE INT,
#PARAM2VALUE INT,
#OUTPARAM VARCHAR(20) OUT)
AS
BEGIN
SELECT * FROM DBO.PARAMTABLENAME WHERE PARAM1VALUE=#PARAM1VALUE
END
DECLARE #OUTPARAM2 VARCHAR(20)
EXEC DBO.MY_STORED_PROCEDURE 1,#OUTPARAM2 OUT
PRINT #OUTPARAM2
Here is the stored procedure
create procedure sp1
(
#id as int,
#name as nvarchar(20) out
)
as
begin
select #name=name from employee where id=#id
end
And here is the way to execute the procedure
declare #name1 nvarchar(10)
exec sp1 1,#name1 out
print #name1
Please check below example to get output variable value by executing a stored procedure.
DECLARE #return_value int,
#Ouput1 int,
#Ouput2 int,
#Ouput3 int
EXEC #return_value = 'Your Sp Name'
#Param1 = value1,
#Ouput1 = #Ouput1 OUTPUT,
#Ouput2 = #Ouput2 OUTPUT,
#Ouput3 = #Ouput3 OUTPUT
SELECT #Ouput1 as N'#Ouput1',
#Ouput2 as N'#Ouput2',
#Ouput3 as N'#Ouput3'
Here is the definition of the stored_proc:
create proc product(#a int,#b int)
as
return #a * #b
And, this is executing it from Python:
conn = pyodbc.connect('...')
cursor = conn.cursor()
sql = """
SET NOCOUNT ON
declare #r float
exec #r=dbo.product 5,4
select #r
"""
result = cursor.execute(sql)
print (result.fetchall())

Resources