Primarily there are two ways to execute a string or a variable in a string format as sql, they are using EXEC and SP_EXECUTESQL.
Using sp_ExecuteSQL, sp_executesql error – Data Type of Vairable
Use AdventureWorks GO DECLARE @SqlStr varchar(500) SET @SqlStr='SELECT TOP 10 EmployeeID,NationalIDNumber,Title FROM HumanResources.Employee' EXEC sp_executesql @SqlStr Msg 214, Level 16, State 2, Procedure sp_executesql, Line 1 Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'.
Using sp_ExecuteSQL, sp_executesql error - Parsed and Compiled
Use AdventureWorks GO DECLARE @SqlStr nvarchar(500) SET @SqlStr='SELECT TOP 10 EmployeeID,A_NationalIDNumber,Title FROM HumanResources.Employee' EXEC sp_executesql @SqlStr Msg 207, Level 16, State 1, Line 1 Invalid column name 'A_NationalIDNumber'.
Using sp_ExecuteSQL,Correct Method
Use AdventureWorks GO DECLARE @SqlStr nvarchar(500) SET @SqlStr='SELECT TOP 10 EmployeeID,NationalIDNumber,Title FROM HumanResources.Employee' EXEC sp_executesql @SqlStr
Using sp_ExecuteSQL, Parameter Concatenation
Use AdventureWorks GO DECLARE @Employeeid int DECLARE @SqlStr nvarchar(500) SET @EmployeeID=10 SET @SqlStr='SELECT TOP 10 EmployeeID,NationalIDNumber,Title FROM HumanResources.Employee WHERE EmployeeID= ' + Cast(@Employeeid as Varchar) EXEC sp_executesql @SqlStr
Using sp_ExecuteSQL, How to Save the result set in a table
USE AdventureWorks GO CREATE TABLE #usp_TestInsertWithSp_exec(EmployeeID int, NationalIDNumber nvarchar(15),Title nvarchar(50)) DECLARE @Employeeid int DECLARE @SqlStr nvarchar(500) SET @EmployeeID=10 SET @SqlStr='SELECT TOP 10 EmployeeID,NationalIDNumber,Title FROM HumanResources.Employee WHERE EmployeeID= ' + Cast(@Employeeid as Varchar) INSERT INTO #usp_TestInsertWithSp_exec EXEC sp_executesql @SqlStr SELECT * FROM #usp_TestInsertWithSp_exec DROP TABLE #usp_TestInsertWithSp_exec
Using sp_ExecuteSQL, OUTPUT Parameters
Use AdventureWorks GO DECLARE @Employeeid int DECLARE @NationalID nvarchar(15) DECLARE @SqlStr nvarchar(500) SET @EmployeeID=10 SET @SqlStr='SELECT @NationalID= NationalIDNumber FROM HumanResources.Employee WHERE EmployeeID= ' + Cast(@Employeeid as Varchar)+'' EXEC sp_executesql @SqlStr, N'@NationalID nvarchar(15) OUTPUT',@NationalID OUTPUT PRINT @NationalID
{ 0 comments }
