I am trying to call a stored procedure in another. The issue is that both use the same variables. How do I get them in the embedded procedure?
CREATE PROCEDURE uspInsert #foo int, #bar int, #cat bit
SET #recId = (SELECT TOP(1) id FROM table WHERE foo = #foo)
IF (#recId IS NULL)
BEGIN INSERT INTO table
END
ELSE
BEGIN
EXEC uspUpdate #foo = #foo, #bar = #bar, #cat = #cat
End
Update proc
CREATE PROCEDURE uspUpdate #foo INT, #bar INT, #cat BIT;
You aren't required to use the names of the parameters when you call a SP, as long as they are in the right order. Try this instead:
CREATE PROCEDURE uspInsert #foo int, #bar int, #cat bit
SET #recId = (SELECT TOP(1) id FROM table WHERE foo = #foo)
IF (#recId IS NULL)
BEGIN INSERT INTO table
END
ELSE
BEGIN
EXEC uspUpdate #foo, #bar, #cat
END
I have a SQL query like this :
ALTER PROCEDURE [dbo].[sp_dynamic_column_list](
#tahun varchar(4),
#bulan varchar(2),
#pks varchar(3))
AS
BEGIN
SET NOCOUNT ON;
DECLARE #totalrow int
DECLARE #inc int = 1
DECLARE #dynamictable NVARCHAR(MAX)
CREATE TABLE #temp
(
tanggal datetime,
)
-- query cari column dulu baru alter table temp diatas
SET #totalrow = dbo.fn_count_row_penerimaan(2014,11,40)
WHILE (#inc <= #totalrow)
BEGIN
ALTER TABLE #temp ADD #inc FLOAT
SET #inc = #inc + 1
END
INSERT INTO #temp
EXEC sp_get_list_penerimaan_pks2 #tahun, #bulan, #pks
SELECT * FROM #temp
DROP TABLE #temp
END
I got error like this:
[Err] 42000 - [SQL Server]Incorrect syntax near '#inc'.
I'm new to SQL Server and like to know the solution for this problem
Thanks in advance
ALTER TABLE my_table ADD #column INT
You need to use Execute statement as mentioned in link.
WHILE #inc <= #totalrow
BEGIN
exec ('ALTER table #temp add '+#inc+' FLOAT set '+#inc+' = '+ #inc+'+1')
END
In a SQL statment variable value cannot be provided as a column name, to achieve this you have to use a dynamic SQL query like the Following:
WHILE (#inc <= #totalrow)
BEGIN
Declare #strquery as varchar(4000)
SET #strquery = 'ALTER TABLE #temp ADD [' + #inc + '] FLOAT'
EXECUTE sp_executesql #strquery -- if #inc =1 then #strQuery : ALTER TABLE #temp ADD [1] FLOAT
SET #inc = #inc + 1
END
You can read more about Dynamic SQL queries in this Article
I have a scenario wherein i have to execute an SP for specified number of time(number of execution will be mentioned by user) without using loop.
My SP is setting an OUTPUT variable of varchar type. I am willing to insert the output of my SP into a temp table and use it for further processing.
I am unable to modify this SP into function as it contain an Update statement.
Kindly suggest if we can do so without loop.
Whit this solution you do not need an output; #res is your result directly set in a temp table.
CREATE PROCEDURE [dbo].[myStoredProc]
#Counter int,
#params nvarchar(64),
#CreateTable bit
AS
DECLARE #res varchar(64)
IF #CreateTable = 1
BEGIN
IF EXISTS (SELECT 1 FROM dbo.sysobjects WHERE id = object_id(N'[#tempTable]'))
DROP TABLE #tempTable
CREATE TABLE #tempTable ([Res] [nvarchar] (64))
END
SET #res = CONVERT(varchar(64), #Counter)
SET #Counter = #Counter - 1
IF #Counter > 0
exec myStoredProc #Counter, #params, 0
INSERT #tempTable VALUES (#res)
IF #CreateTable = 1
BEGIN
SELECT * FROM #tempTable
DROP TABLE #tempTable
END
GO
DECLARE #o varchar(64)
exec [myStoredProc] 5, '', 1
My stored procedure:
ALTER PROCEDURE [dbo].[Perdate]
#D_Data as nvarchar(999)
AS
SELECT 'Total'= SUM(CAST(TBL_Stock.R_TotalPrice as decimal(18,2))),(convert(varchar,TBL_Stock.D_Datepush,105)) as Date
FROM TBL_Stock
GROUP BY (convert(varchar,TBL_Stock.D_Datepush,105))
Having (convert(varchar,TBL_Stock.D_Datepush,105)) = #D_Data
I would like to know if it is possible to set that variable (#D_Data) as something like:
'02-03-2012' or (convert(varchar,TBL_Stock.D_Datepush,105)) = '02-04-2012'
So the having clause would be :
HAVING (convert(varchar, TBL_Stock.D_Datepush, 105)) = '02-03-2012'
OR (convert(varchar, TBL_Stock.D_Datepush, 105)) = '02-04-2012'
So my idea is to have (in my VB.net project) a string that could dynamically change the stored procedure "Future"
Seems like you want to do SQL injection so that your input param "glues into" the TSQL that is being built in your proc. THIS IS A VERY BAD IDEA ( see SQL Injection discussion here).
But good news, dynamic SQL is not needed. Use a table function to parse the incoming string so that it can be joined in the proc.
create table TBL_Stock(R_TotalPrice decimal(18,2), D_Datepush datetime)
insert into TBL_Stock(R_TotalPrice,D_datepush) values(1000,'1/1/2012')
insert into TBL_Stock(R_TotalPrice,D_datepush) values(200,'1/2/2012')
insert into TBL_Stock(R_TotalPrice,D_datepush) values(30,'1/3/2012')
insert into TBL_Stock(R_TotalPrice,D_datepush) values(4,'1/4/2012')
GO
CREATE FUNCTION dbo.SplitDates(#String varchar(8000), #Delimiter char(1))
returns #temptable TABLE (dt datetime)
as
begin
declare #idx int
declare #slice varchar(8000)
select #idx = 1
if len(#String)<1 or #String is null return
while #idx!= 0
begin
set #idx = charindex(#Delimiter,#String)
if #idx!=0
set #slice = left(#String,#idx - 1)
else
set #slice = #String
if(len(#slice)>0 AND isDate(#slice) = 1)
insert into #temptable(dt) values(#slice)
set #String = right(#String,len(#String) - #idx)
if len(#String) = 0 break
end
return
end
GO
--test function
select * from dbo.SplitDates('1/1/2012,1/2/2012',',')
GO
create PROCEDURE Perdate #D_Data as nvarchar(2000)
AS
select
PushDate=z.dt,
'Total'= SUM(s.R_TotalPrice)
from
dbo.splitDates(#D_Data,',') z
join TBL_Stock s on s.D_datepush = z.dt
group by
z.dt
GO
--Test proc
select * from TBL_Stock
exec Perdate '1/1/2012'
exec Perdate '1/1/2012,1/2/2012'
exec Perdate '1/1/2012,1/4/12'
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())