SQL Pass Parameters from One stored proc to another - sql

I have two SQL scripts: Script A and B. Script A retrieves information and uses the sp_executesql command to call stored procedure (Script B). I can successfully accomplish this.
However, now i would like to pass a value from Script A to Script B. I am unable to accomplish this. #nID is the parameter I would like to pass. I am using this link as a reference https://msdn.microsoft.com/en-IN/library/ms188001.aspx
My scripts are attached. For simplicity, I just made my parameter value equal to 5. So how do I pass a '5' from one script to another? Thanks for any help.
Script A
BEGIN
SET NOCOUNT ON;
DECLARE #sp nVARCHAR(25)
DECLARE #nID nvarchar(25)
DECLARE #busID nvarchar(25)
DECLARE #ParmDefinition nvarchar(500)
SET #ParmDefinition = N'#nID nvarchar(50) output ';
set #sp = 'WMCOMM';
set #busID = 5
execute sp_executesql #sp, #ParmDefinition, #nID = #busID;
END
Script B
ALTER PROCEDURE [dbo].[WMCM]
AS
BEGIN
SET nocount ON;
declare #numID nvarchar(50)
insert into tester(numid)
values(#numID)
END

Stored procedure B requires an input parameter
ALTER PROCEDURE [dbo].[WMCM]
#nID nvarchar(25) --DECLARE PARAMETER HERE THEN YOU CAN USE IT IN THE SP
AS
BEGIN
SET nocount ON;
declare #numID nvarchar(50)
insert into tester(numid)
values(#numID)
END
Here's a working template of what you are trying to acheive.
--RUN ME FIRST
CREATE procedure dbo.B
#nID AS NVARCHAR(5)
AS
SELECT #nID
GO
--RUN ME SECOND
CREATE procedure dbo.A
AS
DECLARE #nID NVARCHAR(50) = 'abc'
DECLARE #sp NVARCHAR(50) = 'EXECUTE dbo.B #nID'
EXECUTE sp_executesql #sp,N'#nID NVARCHAR(50)',#nID = #nID;
GO
--RUN ME THIRD
EXEC dbo.a

I dumbed-down the stored procedure to only show and return.
But this does what you want:
alter PROCEDURE [dbo].[WMCM]
#nID nvarchar(25) --DECLARE PARAMETER HERE THEN YOU CAN USE IT IN THE SP
, #InAndOutValue nvarchar(50) OUTPUT
AS
BEGIN
SET nocount ON;
Select '[dbo].[WMCM] has access to :' as ProcName , #nID as TheId
Select '[dbo].[WMCM] can use same variable as input and output. InValue :' as ProcName , #InAndOutValue as TheId
select #InAndOutValue= 'NowImAnOutValue'
END
GO
DECLARE #SQL_String NVARCHAR(max)
DECLARE #Parameter_Definition NVARCHAR(max)
SET #SQL_String = N'
EXEC [dbo].[WMCM] #nID = #nID_input, #InAndOutValue = #InAndOutValue_out OUTPUT
'
SET #Parameter_Definition = N'
#nID_input nvarchar(25),
#InAndOutValue_out nvarchar(50) OUTPUT'
DECLARE #nID nvarchar(25)
DECLARE #InAndOutValue nvarchar(50)
SET #nID = '5'
SET #InAndOutValue = 'InAndOutVariable_JustInValue'
EXECUTE sp_executesql #SQL_String, #Parameter_Definition, #nID_input = #nID, #InAndOutValue_out = #InAndOutValue OUTPUT
SELECT #InAndOutValue as IGotTheInAndOutValue

Related

Is there a way for me to dynamically write a script to add a domain+user to Microsoft SQL server in a stored procedure?

I have to use this exact script below:
ALTER PROCEDURE [dbo].[sp_CheckIfSQLLoginExistsAndCreateLogin]
#SearchDomain NVARCHAR(MAX),
#SearchUsername NVARCHAR(MAX)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #sql NVARCHAR(max);
DECLARE #params NVARCHAR(MAX);
IF #SearchUsername != ''
BEGIN
SET #sql = N'IF NOT EXISTS (SELECT * FROM sys.server_principals WHERE [name] = #Domain\#Username) CREATE LOGIN [#Domain\#Username] FROM WINDOWS';
SET #params = N'#Username NVARCHAR(MAX), #Domain NVARCHAR(MAX)';
END
exec sp_executesql #sql, #params, #Username=#SearchUsername, #Domain=#SearchDomain
END
The problem I am having is that every time this SP is called I get the following error:
Using this data: #SearchDomain = OFFICE and #SearchUsername = BJackson
The problem here is you think SQL is a scripting language; it is not. For example '#Domain' means the literal string '#Domain' not replace the literal string '#Domain' with the value in the variable #Domain.
If you have EXEC sys.sp_executesql N'SELECT '#V1 + #V2';', N'#V1 varchar(30), #V2 varchar(30)','This', 'works'; you don't get the value 'Thisworks' you get the value '#V1 + #V2' Why? Because they are literals.
What you need to do is safely inject your parameters for the object names, and properly parametrise your WHERE:
ALTER PROCEDURE [dbo].[CheckIfSQLLoginExistsAndCreateLogin] --removed prefix
#SearchDomain sysname, --Corrected datatype
#SearchUsername sysname --Corrected datatype
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #sql NVARCHAR(max);
DECLARE #Login sysname = CONCAT(#SearchDomain,'\',#SearchUsername);
IF #Login != ''
BEGIN
SET #sql = N'IF NOT EXISTS (SELECT * FROM sys.server_principals WHERE [name] = #Login) CREATE LOGIN ' + QUOTENAME(Login) + N' FROM WINDOWS';
END
EXEC sys.sp_executesql #sql, N'#Login sysname', #Login;
END;
Here is a simple example:
CREATE OR ALTER PROCEDURE [dbo].[sp_CheckIfSQLLoginExistsAndCreateLogin]
#SearchDomain NVARCHAR(MAX),
#SearchUsername NVARCHAR(MAX)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #sql NVARCHAR(max);
DECLARE #params NVARCHAR(MAX);
IF #SearchUsername != ''
BEGIN
SET #sql = N'IF NOT EXISTS (SELECT * FROM sys.server_principals WHERE [name] = '''+ #SearchDomain +'\'+ #SearchUsername +''') CREATE LOGIN [#Domain\#Username] FROM WINDOWS';
SET #params = N'#Username NVARCHAR(MAX), #Domain NVARCHAR(MAX)';
END
exec sp_executesql #sql, #params, #Username=#SearchUsername, #Domain=#SearchDomain
END

Must declare scalar variable in sql server dynamic sql

I am having problems running sql server stored procedure. I using a dynamic sql.
I get the error "Must declare the scalar variable "#EmployeeId".
SQL QUERY
ALTER PROCEDURE [dbo].[GetLeaveDays] -- Add the parameters for the stored
procedure here
#LeaveType varchar(5000),
#AdminId int,
#EmployeeId int
AS
BEGIN
SET NOCOUNT ON;
DECLARE
#queryString nvarchar(MAX);
SET #queryString = 'SELECT ' + #LeaveType + ' FROM CompulsoryLeave WHERE
AdminId = #AdminId AND Id=(SELECT LeaveStructureId FROM Employee WHERE
Id=#EmployeeId)';
EXECUTE sp_executesql #queryString,
N'#AdminId int',
N'#EmployeeId int',
#AdminId = #AdminId,
#EmployeeId=#EmployeeId
END
The second sp_executesql parameter should be a single string with all parameter definitions. Try:
EXECUTE sp_executesql #queryString,
N'#AdminId int, #EmployeeId int',
#AdminId = #AdminId,
#EmployeeId = #EmployeeId;

Dynamic Name for Database Table - Stored Procedure

I want to create dynamic name for my database tables. I declare variable and use it as my table name.
ERROR: Incorrect syntax near '#sample'. Expecting '.',ID or QUOTED_ID
CREATE PROCEDURE [dbo].[sp_SAMPLE]
#name nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sample nvarchar(50);
SET #sample = 'tbl_function_' + #name;
Create Table #sample
(
id int not null,
UserType nvarchar(50) null,
paramater2 nvarchar(50) null
)
END
Is there any way to make my table name dynamic? Thank you.
I'm not sure why you would want to do this. But, you can do it using dynamic SQL:
CREATE PROCEDURE [dbo].[sp_SAMPLE]
#name nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql nvarchar(max);
SET #sql = '
Create Table tbl_function_#name
(
id int not null,
UserType nvarchar(50) null,
paramater2 nvarchar(50) null
)';
SET #sql = REPLACE(#sql, '#name', #name);
EXEC sp_executesql #sql;
END;
Why would you want to create a separate table for each #name, instead of just inserting rows with #name in a column?
CREATE PROCEDURE [dbo].[sp_SAMPLE]
#name nvarchar(50)
AS
BEGIN
SET NOCOUNT ON
DECLARE #sql varchar(4000);
SET #sql = '
Create Table tbl_function_'+#name+'
(
id int not null,
UserType nvarchar(50) null,
paramater2 nvarchar(50) null
)'
EXEC (#sql)
END

i want to pass a select query in a stored procedure as an argumnet

I made this procedure..
ALTER PROCEDURE [dbo].[MyProcedure]
#pSelect nvarchar
AS
BEGIN
SET NOCOUNT ON;
select #pSelect from tabel1
END
I want to pass a select query like from c# code to this stored procedure
MyProcedure("column1,column2");
How could I do this because stored procedure treat my parameter as a string and it behaves like
select N'column1,column2' from tabel1
pls help me
or provide a better option for this
You'll have to use dynamic sql inside the stored procedure.
ALTER PROCEDURE [dbo].[MyProcedure]
#pSelect nvarchar(max)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SQL nvarchar(max)
SET #SQL = 'select ' + #pSelect + ' from tabel1';
EXEC (#SQL)
END
Here's a script to test the above stored procedure:
CREATE TABLE tabel1 (id int, data varchar(50))
INSERT INTO tabel1 VALUES(1,'aaa'),(2,'bbb'),(3,'ccc')
EXEC [dbo].[MyProcedure] 'id'
EXEC [dbo].[MyProcedure] 'data'
EXEC [dbo].[MyProcedure] 'id,data'
You can use dynamic SQL for the purpose, but it is not recommended. (More info here - The Curse and Blessings of Dynamic SQL)
create procedure MyProcedure
#pSelect nvarchar
AS
begin
declare #sql nvarchar(4000);
set #sql='select ['+ #pSelect +'] from Table_1';
exec sp_executesql #sql
end
go
exec MyProcedure 'column1,column2'
go
If your #pSelect is having entire query then:
ALTER PROCEDURE [dbo].[MyProcedure]
#pSelect nvarchar
AS
BEGIN
SET NOCOUNT ON;
-- If you are#pSelect is having entire query
exec (#pSelect)
-- If you are passing only field list then following
DECLARE #SQL nvarchar(max)
SET #SQL = 'select ' + #pSelect + ' from tabel1';
END

Pass a TABLE variable to sp_executesql

I'm trying to pass a TABLE variable to the sp_executesql procedure:
DECLARE #params NVARCHAR(MAX)
SET #params = '#workingData TABLE ( col1 VARCHAR(20),
col2 VARCHAR(50) )'
EXEC sp_executesql #sql, #params, #workingData
I get the error:
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'TABLE'.
I tried omitting the column specification after 'TABLE'. I also tried to declare the table as a variable inside the dynamic SQL. But no luck...
Seems to me that TABLE variables aren't allowed to be passed as parameters in this procedure?. BTW: I'm running MSSQL2008 R2.
I'm not interested in using a local temp table like #workingData because I load the working data from another procedure:
INSERT INTO #workingData
EXEC myProc #param1, #param2
Which I cannot do directly into a temp varaible (right?)...
Any help appreciated!
If you are using SQL Server 2008, to pass a table variable to a stored procedure you must first define the table type, e.g.:
CREATE TYPE SalesHistoryTableType AS TABLE
(
[Product] [varchar](10) NULL,
[SaleDate] [datetime] NULL,
[SalePrice] [money] NULL
)
GO
or use an existing table type stored in the database.
Use this query to locate existing table types
SELECT * FROM sys.table_types
To use in an stored procedure, declare an input variable to be the table:
CREATE PROCEDURE usp_myproc
(
#TableVariable SalesHistoryTableType READONLY
)
AS BEGIN
--Do stuff
END
GO
Populate the table variable before passing to the stored procedure:
DECLARE #DataTable AS SalesHistoryTableType
INSERT INTO #DataTable
SELECT * FROM (Some data)
Call the stored procedure:
EXECUTE usp_myproc
#TableVariable = #DataTable
Further discussions here.
OK, this will get me what I want, but surely isn't pretty:
DECLARE #workingData TABLE ( col1 VARCHAR(20),
col2 VARCHAR(20) )
INSERT INTO #workingData
EXEC myProc
/* Unfortunately table variables are outside scope
for the dynamic SQL later run. We copy the
table to a temp table.
The table variable is needed to extract data directly
from the strored procedure call above...
*/
SELECT *
INTO #workingData
FROM #workingData
DECLARE #sql NVARCHAR(MAX)
SET #sql = 'SELECT * FROM #workingData'
EXEC sp_executesql #sql
There must be a better way to pass this temporary resultset into sp_executesql!?
Regards
Alex
While this may not directly answer your question, it should solve your issue overall.
You can indeed capture the results of a Stored Procedure execution into a temporary table:
INSERT INTO #workingData
EXEC myProc
So change your code to look like the following:
CREATE TABLE #workingData ( col1 VARCHAR(20),
col2 VARCHAR(20) )
INSERT INTO #workingData
EXEC myProc
DECLARE #sql NVARCHAR(MAX)
SET #sql = 'SELECT * FROM #workingData'
EXEC sp_executesql #sql
Regards,
Tim
Alter PROCEDURE sp_table_getcount
#tblname nvarchar(50) ,
#totalrow int output
AS
BEGIN
Declare #params nvarchar(1000)
Declare #sql nvarchar(1000)
set #sql = N'Select #cnt= count(*) From #tbl'
set #params = N'#tbl nvarchar(50) , #cnt int OUTPUT'
Exec sp_executesql #sql , #params ,#tbl=#tblname , #cnt = #totalrow OUTPUT
END
GO
Please note that the above code will not work as table as a object is out of the scope.It will give you the error: must declare table variable.In order to work around we can do the following.
Alter PROCEDURE sp_table_getcount
#tblname nvarchar(50) ,
#totalrow int output
AS
BEGIN
Declare #params nvarchar(1000)
Declare #sql nvarchar(1000)
set #sql = N'Select #cnt= count(*) From dbo.' + #tblname
set #params = N'#cnt int OUTPUT'
Exec sp_executesql #sql , #params , #cnt = #totalrow OUTPUT
END
GO
So-called TableType is tricky. #Alex version should work. However, to simplify and faster performance, go check sys.tables for matching table name while not compromise security and performance.
Here it is
create proc [dbo].Test11
#t1 AS nvarchar(250), #t2 nvarchar(250)
AS
BEGIN
SET nocount ON;
DECLARE #query AS nvarchar(MAX)
if exists (select * from sys.tables where name = #t1) and
exists (select * from sys.tables where name = #t2)
begin
SET #query = N'select * FROM '+ #t1 + N' join ' + #t2 + N' ON ...' ;
select 'Safe and fast'
print #query
exec sp_executesql #query
end
else
select 'Bad, no way Jose.'
SET nocount OFF;
END
GO