Table variable in sp_executesql parameter list - tsql

I'm having trouble sending a table variable into a sp_executesql parameter list.
my Table Variable:
declare #MemberCoverageIds table (CoverageId ID_t)
insert into #MemberCoverageIds( CoverageId) select MemberCoverageId from MemberCoverages where MemberNumber = #FulfillmentEntityIdentifier
My where clause using the table variable:
#WhereClause = #WhereClause + 'and F.FulfillmentEntityId in (select CoverageId from #MemberCoverageIds) '
it is part of my FinalSQL variable which has the rest of the statement:
select #FinalSQL = #InsertClause + #SelectClause + #JoinClause + #WhereClause
and then I have the execute:
exec sp_executesql #FinalSQL,
N' #FulfillmentEntityIdentifier RefNumber_t,
#MemberCoverageIds ReadOnly,
#EntityId Id_t,
#FulfillmentEntityType Code_t,
#FulfillmentDocumentType Code_t,
#FulfillmentMethod Code_t',
#FulfillmentEntityIdentifier = #FulfillmentEntityIdentifier,
#MemberCoverageIds = #MemberCoverageIds,
#EntityId = #EntityId,
#FulfillmentEntityType = #FulfillmentEntityType,
#FulfillmentDocumentType = #FulfillmentDocumentType,
#FulfillmentMethod = #FulfillmentMethod
I then get an unexpected error from that execution. I know it is the #MemberCoverages table variable because it worked before I added it. My question is what would be the proper syntax for sending the table variable in the parameter list? Do I have to declare it in the Parameter list?

You need to create a named type that your table variable will use:
create type dbo.myTableType as table (id int)
Then you can use it as a typed argument to sp_executesql:
declare #m dbo.myTableType;
insert #m values (1), (2)
exec sp_executesql
N'select 99 where 1 in (select id from #m)',
N'#m dbo.myTableType readonly',
#m
If you don't want to create a new type, you can use a #temp table:
declare #t table(id int);
insert #t values (1), (2);
select * into #t from #t;
exec sp_executesql N'select 99 where 1 in (select id from #t)';

Related

TSQL - How to output the content of a variable into a table?

As described in the title, I'm looking to store the output of a variable into a "non-variable table". Here is the code:
declare #fullpath NVARCHAR(200) = '''Data Source=path\to\folder\'
declare #filename NVARCHAR(50) = 'Country.xlsx'
declare #properties NVARCHAR(50) = ';Extended Properties=Excel 12.0'')'
declare #sheetname NVARCHAR(50) = '...[Country$]'
declare #extraction NVARCHAR(500) =
'SELECT * FROM OPENDATASOURCE(''Microsoft.ACE.OLEDB.12.0'','+ #fullpath+
#filename+
#properties+
#sheetname
EXEC(#extraction)
This will output the content of the excel file in table format (country_id and country_name). Now, how would one store this output table in another table? For instance:
SELECT * INTO #temp FROM #extraction
Regards,
Just use INSERT INTO as you normally would. INSERT INTO allows for it to be followed by an EXEC statement:
CREATE TABLE #Temp ({Column List});
INSERT INTO #Temp ({Column List})
EXEC sys.sp_executsql #extraction;
Seems like the OP doesn't know the definition of the files. This, in truth, is a problem, but you can "get around" it. I would therefore SELECT ... INTO inside the dynamic statement. You'll need to use a global temporary table, or a user table for this though. I use a global temporary table for this example:
DECLARE #extraction nvarchar(MAX) =
N'SELECT * INTO ##TEMP FROM OPENDATASOURCE(''Microsoft.ACE.OLEDB.12.0'',' + #fullpath + #filename + #properties + #sheetname;
EXEC sys.sp_executesql #SQL;
SELECT *
FROM ##TEMP;
--DROP TABLE ##TEMP;

How to Get output from nested SP_executeSQL

Can you tell me how to insert executed variable #name in my table?
I had some coding and this is what i managed to do but I do not know whats next:
DECLARE #Name nvarchar(200);
DECLARE #dbcatalog nvarchar(128);
declare #sql nvarchar(4000)
select #name = N' select ID from ' + #DbCatalog + '.dbo.Table2 ';
SET #sql = 'insert into Table2(Name) values (#name)'
exec Sp_executeSQL #sql
Are you trying to copy ID values from one table into another? If so, then:
INSERT INTO Table2 (Name)
EXEC(#Name)

How to use sp_execute passing table parameter

I need to pass a table var to sp_executesql statement. Do you know how can I pass the table variable to sp_executesql?
Here is how I pass the regular variable (not table variable) to sp_executesql
EXEC sp_executesql #statement, N'#Status INT',#Status
Typically you don't pass a table variable to execute SQL with sp_executesql. You make a statement up out of text and execute that. Like so:
IF OBJECT_ID('tempdb..#People') IS NOT NULL
DROP TABLE tempdb..#People
CREATE TABLE #People (PersonId INT IDENTITY, PersonName VARCHAR(128));
INSERT INTO #People (PersonName) VALUES ('Brett'), ('John'), ('Mark'), ('Shawn'), ('Ryan'), ('Kevin');
DECLARE #SQL NVARCHAR(Max) = 'Select * from #People'
EXEC sp_executesql #Sql
UPDATE 1-27-17
IF OBJECT_ID('tempdb..#People') IS NOT NULL DROP TABLE tempdb..#People
IF OBJECT_ID('tempdb..#People2') IS NOT NULL DROP TABLE tempdb..#People2
CREATE TABLE #People (PersonId INT IDENTITY, PersonName VARCHAR(128));
CREATE TABLE #People2 (PersonId INT IDENTITY(7,1), PersonName VARCHAR(128));
SET NOCOUNT ON;
INSERT INTO #People (PersonName) VALUES ('Brett'), ('John'), ('Mark'), ('Shawn'), ('Ryan'), ('Kevin');
INSERT INTO #People2 (PersonName) VALUES ('Emily'), ('Beth'), ('Jane'), ('Hannah');
--I. getting an output for a single output variable dynamically
--Say I just want to get Ryan by his Id dynamically and output it
--I need to define one or many parameters OUTSIDE the scope of the Dynamic Sql
DECLARE #Output VARCHAR(8)
DECLARE #PersonId INT = 5
--I then need to associate the parameters as an array, for the purposes of explanation I will use DIFFERENT NAMES you may use the same
DECLARE #ParmDefinition NVARCHAR(500) = N'#PersonIdInside Int, #OutputInside varchar(8) OUTPUT'
--I then use the names ABOVE in the dynamic sql
DECLARE #SQL NVARCHAR(Max) = N'Select #OutputInside = PersonName from #People Where PersonId = #PersonIdInside'
-- I then do the following AFTER the sp_executesql 1. The Dynamic sql nvarchar, 2. The params nvarchar 3. one or many variables and how they associate
EXEC sp_executesql #Sql, #ParmDefinition, #PersonIdInside = #PersonId, #OutputInside = #Output OUTPUT
-- I have an output so now it should show what I want
SELECT #Output
-- II. getting a result set dymamically to another record set or table OUTSIDE the scope of the internal
-- Create another table, I use a #table for example purposes
IF OBJECT_ID('tempdb..#Output') IS NOT NULL DROP TABLE tempdb..#Output
CREATE TABLE #Output (PersonId INT IDENTITY, PersonName VARCHAR(8))
--Get a truncated list for an 'in' statement later of person Id's in a variable
DECLARE #People NVarchar(32) = N'1, 5, 10'
--I then use the #People ABOVE in the dynamic sql putting it together and then do an 'insert statement first'
DECLARE #SQL2 NVARCHAR(Max) = N'Insert Into #Output SELECT PersonName FROM (SELECT * FROM #People UNION SELECT * FROM #People2) as x Where PersonId in (' + #People + ')'
--execute yields nothing
EXEC sp_executesql #Sql2
-- or does it?
Select *
From #Output
-- !!! WARNING !!!
-- With dynamic sql you cannot nest multiple dynamic sql statements inside of procs. EG: Proc1 cannot call Proc2 and both of them have dynamic sql in them. Engine limitation.

How to get row count from EXEC() in a TSQL SPROC?

I have a TSQL sproc that builds a query as and executes it as follows:
EXEC (#sqlTop + #sqlBody + #sqlBottom)
#sqlTop contains something like SELECT TOP(x) col1, col2, col3...
TOP(x) will limit the rows returned, so later I want to know what the actual number of rows in the table is that match the query.
I then replace #sqlTop with something like:
EXEC ('SELECT #ActualNumberOfResults = COUNT(*) ' + #sqlBody)
I can see why this is not working, and why a value not declared error occurs, but I think it adequately describes what I'm trying to accomplish.
Any ideas?
use sp_executesql and an output parameter
example
DECLARE #sqlBody VARCHAR(500),#TableCount INT, #SQL NVARCHAR(1000)
SELECT #sqlBody = 'from sysobjects'
SELECT #SQL = N'SELECT #TableCount = COUNT(*) ' + #sqlBody
EXEC sp_executesql #SQL, N'#TableCount INT OUTPUT', #TableCount OUTPUT
SELECT #TableCount
GO
You could instead have the dynamic query return the result as a row set, which you would then insert into a table variable (could be a temporary or ordinary table as well) using the INSERT ... EXEC syntax. Afterwards you can just read the saved value into a variable using SELECT #var = ...:
DECLARE #rowcount TABLE (Value int);
INSERT INTO #rowcount
EXEC('SELECT COUNT(*) ' + #sqlBody);
SELECT #ActualNumberOfResults = Value FROM #rowcount;
Late in the day, but I found this method much simpler:
-- test setup
DECLARE #sqlBody nvarchar(max) = N'SELECT MyField FROM dbo.MyTable WHERE MyOtherField = ''x''';
DECLARE #ActualNumberOfResults int;
-- the goods
EXEC sp_executesql #sqlBody;
SET #ActualNumberOfResults = ##ROWCOUNT;
SELECT #ActualNumberOfResults;
After executing your actual query store the result of ##ROWCOUNT in any variable which you can use later.
EXEC sp_executesql 'SELECT TOP 10 FROM ABX'
SET #TotRecord = ##ROWCOUNT into your variable for later use.
Keep in mind that dynamic SQL has its own scope. Any variable declared/modified there will go out of scope after your EXEC or your sp_executesql.
Suggest writing to a temp table, which will be in scope to your dynamic SQL statement, and outside.
Perhaps put it in your sqlBottom:
CREATE TABLE ##tempCounter(MyNum int);
EXEC('SELECT #ActualNumberOfResults = COUNT(*) ' + #sqlBody +
'; INSERT INTO ##tempCounter(MyNum) VALUES(#ActualNumberOfResults);');
SELECT MyNum FROM ##tempCounter;
You can use output variable in SP_EXECUTESQL
DECLARE #SQL NVARCHAR(MAX);
DECLARE #ParamDefinition NVARCHAR(100) = '#ROW_SQL INT OUTPUT'
DECLARE #AFFECTED_ROWS INT;
SELECT
#SQL = N'SELECT 1 UNION ALL SELECT 2'
SELECT #SQL += 'SELECT #ROW_SQL = ##ROWCOUNT;';
EXEC SP_EXECUTESQL #SQL, #ParamDefinition, #ROW_SQL=#AFFECTED_ROWS OUTPUT;
PRINT 'Number of affected rows: ' + CAST(#AFFECTED_ROWS AS VARCHAR(20));
Ouput:
SQL2.sql: Number of affected rows: 2
Thanks Jesus Fernandez!
The only problem with the answers that create temporary tables (either using "DECLARE #rowcount TABLE" or "CREATE TABLE ##tempCounter(MyNum int)") is that you're having to read all the affected records off disk into memory. If you're expecting a large number of records this may take some time.
So if the answer is likely to be large the "use sp_executesql and an output parameter" solution is a more efficient answer. And it does appear to work.

How to get sp_executesql result into a variable?

I have a piece of dynamic SQL I need to execute, I then need to store the result into a variable.
I know I can use sp_executesql but can't find clear examples around about how to do this.
If you have OUTPUT parameters you can do
DECLARE #retval int
DECLARE #sSQL nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
DECLARE #tablename nvarchar(50)
SELECT #tablename = N'products'
SELECT #sSQL = N'SELECT #retvalOUT = MAX(ID) FROM ' + #tablename;
SET #ParmDefinition = N'#retvalOUT int OUTPUT';
EXEC sp_executesql #sSQL, #ParmDefinition, #retvalOUT=#retval OUTPUT;
SELECT #retval;
But if you don't, and can not modify the SP:
-- Assuming that your SP return 1 value
create table #temptable (ID int null)
insert into #temptable exec mysp 'Value1', 'Value2'
select * from #temptable
Not pretty, but works.
DECLARE #vi INT
DECLARE #vQuery NVARCHAR(1000)
SET #vQuery = N'SELECT #vi= COUNT(*) FROM <TableName>'
EXEC SP_EXECUTESQL
#Query = #vQuery
, #Params = N'#vi INT OUTPUT'
, #vi = #vi OUTPUT
SELECT #vi
DECLARE #tab AS TABLE (col1 VARCHAR(10), col2 varchar(10))
INSERT into #tab EXECUTE sp_executesql N'
SELECT 1 AS col1, 2 AS col2
UNION ALL
SELECT 1 AS col1, 2 AS col2
UNION ALL
SELECT 1 AS col1, 2 AS col2'
SELECT * FROM #tab
Return values are generally not used to "return" a result but to return success (0) or an error number (1-65K). The above all seem to indicate that sp_executesql does not return a value, which is not correct. sp_executesql will return 0 for success and any other number for failure.
In the below, #i will return 2727
DECLARE #s NVARCHAR(500)
DECLARE #i INT;
SET #s = 'USE [Blah]; UPDATE STATISTICS [dbo].[TableName] [NonExistantStatisticsName];';
EXEC #i = sys.sp_executesql #s
SELECT #i AS 'Blah'
SSMS will show this
Msg 2727, Level 11, State 1, Line 1
Cannot find index 'NonExistantStaticsName'.
If you want to return more than 1 value use this:
DECLARE #sqlstatement2 NVARCHAR(MAX);
DECLARE #retText NVARCHAR(MAX);
DECLARE #ParmDefinition NVARCHAR(MAX);
DECLARE #retIndex INT = 0;
SELECT #sqlstatement = 'SELECT #retIndexOUT=column1 #retTextOUT=column2 FROM XXX WHERE bla bla';
SET #ParmDefinition = N'#retIndexOUT INT OUTPUT, #retTextOUT NVARCHAR(MAX) OUTPUT';
exec sp_executesql #sqlstatement, #ParmDefinition, #retIndexOUT=#retIndex OUTPUT, #retTextOUT=#retText OUTPUT;
returned values are in #retIndex and #retText
Declare #variable int
Exec #variable = proc_name
DECLARE #ValueTable TABLE
(
Value VARCHAR (100)
)
SELECT #sql = N'SELECT SRS_SizeSetDetails.'+#COLUMN_NAME+' FROM SRS_SizeSetDetails WHERE FSizeID = '''+#FSizeID+''' AND SRS_SizeSetID = '''+#SRS_SizeSetID+'''';
INSERT INTO #ValueTable
EXEC sp_executesql #sql;
SET #Value='';
SET #Value = (SELECT TOP 1 Value FROM #ValueTable)
DELETE FROM #ValueTable
This worked for me:
DECLARE #SQL NVARCHAR(4000)
DECLARE #tbl Table (
Id int,
Account varchar(50),
Amount int
)
-- Lots of code to Create my dynamic sql statement
insert into #tbl EXEC sp_executesql #SQL
select * from #tbl
Here's something you can try
DECLARE #SqlStatement NVARCHAR(MAX) = ''
,#result XML
,#DatabaseName VARCHAR(100)
,#SchemaName VARCHAR(10)
,#ObjectName VARCHAR(200);
SELECT #DatabaseName = 'some database'
,#SchemaName = 'some schema'
,#ObjectName = 'some object (Table/View)'
SET #SqlStatement = '
SELECT #result = CONVERT(XML,
STUFF( ( SELECT *
FROM
(
SELECT TOP(100)
*
FROM ' + QUOTENAME(#DatabaseName) +'.'+ QUOTENAME(#SchemaName) +'.' + QUOTENAME(#ObjectName) + '
) AS A1
FOR XML PATH(''row''), ELEMENTS, ROOT(''recordset'')
), 1, 0, '''')
)
';
EXEC sp_executesql #SqlStatement,N'#result XML OUTPUT', #result = #result OUTPUT;
SELECT DISTINCT
QUOTENAME(r.value('fn:local-name(.)', 'VARCHAR(200)')) AS ColumnName
FROM #result.nodes('//recordset/*/*') AS records(r)
ORDER BY ColumnName
This was a long time ago, so not sure if this is still needed, but you could use ##ROWCOUNT variable to see how many rows were affected with the previous sql statement.
This is helpful when for example you construct a dynamic Update statement and run it with exec. ##ROWCOUNT would show how many rows were updated.
Here is the definition