I wrote a procedure in order to insert the same row into 2 different tables (one table for the sender of the message and an other for the receiver)
CREATE PROCEDURE InsertMsg
#tablesrc VARCHAR(50),
#tabeldest VARCHAR(50),
#src VARCHAR(50),
#dest VARCHAR(50),
#contenu VARCHAR(500)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Sql NVARCHAR(MAX);
SET #Sql = N'INSERT INTO '+ QUOTENAME(#tablesrc)+' (src,dest,contenu,dateEnvoi,Vu) values (#src,#dest,#contenu,GETDATE(),0)'
+ N'INSERT INTO '+ QUOTENAME(#tabeldest)+' (src,dest,contenu,dateEnvoi,Vu) values (#src,#dest,#contenu,GETDATE(),0)'
EXECUTE sp_executesql #Sql
END
Execution
execute InsertMsg 'MSG_RS_80f355a2', 'MSG_RS_80f355a2', 'RS_80f355a2', 'RS_80f355a2', 'test procedure'
I get this error:
Must declare the scalar variable "#src"
You aren't passing the values of your variables #src,#dest and #contenu to sp_executesql. You need to parametrise the statement:
EXECUTE sp_executesql #Sql,
N'#srv varchar(50), #dest varchar(50), #contenu varchar(500)',
#srv = #srv,
#dest = #dest,
#contenu = #contenu;
Create Function fnRMatrixColorGet1(
#RMID varchar(20)
)
returns varchar(100)
as
begin
EXEC (N'SELECT ' + 'C'+#RMID + ' FROM vwemployeeget where empid='+#RMID)
return
end
As Gordon wrote in the comments, user defined functions in SQL Server can't execute dynamic SQL.
From Create User-defined Functions:
User-defined functions cannot make use of dynamic SQL or temp tables. Table variables are allowed.
However, you can create a stored procedure to do that:
CREATE PROCEDURE stpRMatrixColorGet1
(
#RMID varchar(20)
#MatrixColor varchar(100) OUTPUT
)
AS
DECLARE #Sql nvarchar(4000),
#Column sysname = N'C' + #RMID;
-- White list column name since it can't be parameterized
IF EXISTS
(
SELECT 1
FROM Information_Schema.Columns
WHERE Table_Name = 'vwemployeeget'
AND Column_Name = #Column
)
BEGIN
SET #SQL = N'SELECT #MatrixColor = QUOTENAME('+ #Column +') FROM vwemployeeget where empid = #RMID'
-- Safely execute dynamic SQL using sp_ExecuteSql
EXEC sp_ExecuteSql
#Sql,
N'#RMID varchar(20), #MatrixColor varchar(100) OUTPUT',
#RMID,
#MatrixColor OUTPUT
END
I have to truncate the table but getting error
Must declare the scalar variable "#Table".
Code:
DECLARE #Table VARCHAR(20) = 'ABC'
AS
BEGIN
EXEC ('TRUNCATE TABLE abcDB.dbo.'+#Table) AT [Server]
END
Declare the varaible After AS keyword.
BEGIN
DECLARE #Table VARCHAR(20) = 'ABC'
EXEC ('TRUNCATE TABLE abcDB.dbo.'+#Table) AT [Server]
END
Check if u have any constraints(Foreign key). If exists drop it
DECLARE #Table VARCHAR(20) = 'ABC'
BEGIN
EXEC ('TRUNCATE TABLE abcDB.dbo.'+#Table)
END
Use sp_executesql:
DECLARE #Table VARCHAR(20) = 'ABC'
SET #sql='TRUNCATE TABLE abcDB.dbo.' + #Table
EXEC sp_executesql #sql
tables:
create table TabA
(ID int, Name varchar(20))
insert into TabA
select 1,'ABC' union
select 2,'DEF' union
select 3,'GHD'
create table TabB
(ID int, Name varchar(20))
insert into TabA
select 1,'XYZ' union
select 2,'STF' union
select 3,'LDZ'
create table status
(Result1 int,Result2 int )
Create table query(query1 varchar(1000),query2 varchar(1000))
Insert into query(query1,query2)
select '''select COUNT(*) from TabA''','''select COUNT(* )from TabB'''
select * from query
procedure:
create Procedure [dbo].spStatus
AS
BEGIN
SET NOCOUNT ON;
Declare #sqlString1 nvarchar(1000)
,#sqlString2 nvarchar(1000)
,#col_value1 varchar(256)
,#col_value2 varchar(256)
select #sqlString1 = query1
, #sqlString2 =query2
from Query
EXEC sp_executesql
#query=#sqlString1, --sql string is your full select statement
#params = N'#col_Value1 varchar(256) OUTPUT',
#col_Value1 = #col_Value1 OUTPUT
print(#sqlString1)
-- #sqlString2, --sql string is your full select statement
--#params = N'#col_Value2 varchar(256) OUTPUT',
-- #col_Value2 = #col_Value2 OUTPUT
Insert Into dbo.Status(Result1,Result2 )
Values(#col_Value1,#col_Value2)
End
It works if we use #query=#sqlString1 only but I want both statement #query=#sqlString1,#query=#sqlString2 should execute together.
Please help how can we use both statement to execute?
Thanks in Advance
Did you mean:
SET #sqlString1 = #sqlString1 + ';' + #sqlString2;
EXEC sp_executesql #query = #sqlString1 --...
Concat the two queries together with a + (#query=#sqlString1 + '; ' + #sqlString2)
Then use two variables to capture the two counts into output variables
OR
Insert into query(query1,query2)
EXEC sp_executesql 'SELECT ( select COUNT(*) from TabA ) AS query1, ( select COUNT(*)from TabB ) AS query2'
... but really and truly dynamic SQL isn't needed for that at all.
try this:
--add this
DECLARE #SQL nvarchar(max)
SET #SQL=ISNULL(#sqlString1,'')+';'+ISNULL(#sqlString2,'')
--change this
EXEC sp_executesql #query=#SQL
,#params = N'#col_Value1 varchar(256) OUTPUT'
,#col_Value1 = #col_Value1 OUTPUT
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())