In SQL scripting, it is a common scenario when you need to pass parameters to a stored procedure using select command and we have multiple solutions for this. But before proceeding with the solutions, I need to create a table and a stored procedure to demonstrate the solution.
USE AdventureWorks2012 GO --Create table CREATE TABLE dbo.[Department_Audit] ( DepartmentID smallint, Name nvarchar(50), ) GO --Create Stored Procedure CREATE PROCEDURE dbo.Usp_Department_Audit @DepartmentID int, @Name varchar(50) AS BEGIN INSERT INTO [Department_Audit] VALUES(@DepartmentID,@Name) END
Solution 1 :
In this solution you need to use extra variable to take the values from SELECT command and insert into a STORED PROCEDURE.
Given below is the solution.
USE AdventureWorks2012 GO --Declare variables DECLARE @DepartmentID int DECLARE @Name varchar(50) --Set value to variables SELECT @DepartmentID=[DepartmentID],@Name=[Name] FROM HumanResources.Department Where [DepartmentID]=1 --pass variables to stored procedure and execute it. EXEC dbo.Usp_Department_Audit @DepartmentID,@Name GO USE AdventureWorks2012 GO --Browse the table SELECT * FROM [Department_Audit] GO --OUTPUT
Solution 2 :
In this solution you do not need to use extra variable to take the values from SELECT command and insert into a STORED PROCEDURE. You can make a dynamic SQL string and insert the records directly into the STORED PROCEDURE using SELECT command. Given below is the solution.
USE AdventureWorks2012 GO DECLARE @SQL nvarchar(max) SET @SQL = '' SELECT @SQL = @SQL + 'EXEC dbo.Usp_Department_Audit ' + Convert(nvarchar(2),[DepartmentID]) + ', ' + '''' + [Name] + '''' + '; ' FROM HumanResources.[Department] Where [DepartmentID] =2 EXEC (@SQL) USE AdventureWorks2012 GO SELECT * FROM [Department_Audit] --OUTPUT
Leave a Reply