Get results for EXECUTE(#QUERY) and FOR XML - sql-server

I have a dynamic query with FOR XML clause.
How can I get result from it ?
DECLARE #QUERY NVARCHAR(MAX);
-- Here dynamicaly generated query. But for example i made it static
SET #QUERY = N'SELECT [CLMN]
FROM (
SELECT 1 as [CLMN]
) TBL FOR XML PATH(''TBL'')';
EXECUTE(#QUERY);
I need insert result to any variable from this code:
EXECUTE(#QUERY);

You can do it like this:
declare #QUERY nvarchar(max), #RESULT xml
set #QUERY = N'select #RESULT = (
SELECT [CLMN]
FROM (
SELECT 1 as [CLMN]
) TBL
FOR XML PATH(''TBL'')
)'
execute sp_executesql #QUERY, N'#RESULT xml output', #RESULT = #RESULT output
select #RESULT
Just pass outer variable into dynamic query, and assign result of select ... for xml to this variable in query.

Related

How to store the result of exec in a variable

How can I store the result of exec in a variable? The output is JSON.
My SQL query is complex and dynamically generated, so I have to set a variable and execute it.
create PROCEDURE dbo.RetrievePerfCounterData #jsonOutput NVARCHAR(MAX) OUTPUT
AS
BEGIN
declare #sql NVARCHAR(MAX)
SET #sql = ' SELECT TOP (1) getdate() AS ''dateTime'' ,suser_sname()AS ''user'' FOR JSON PATH '
exec (#sql)
END
Here's my attempt at storing the data in a variable:
DECLARE #json AS NVARCHAR(MAX)
EXEC dbo.RetrievePerfCounterData #jsonOutput = #json OUTPUT
DECLARE #myVar VARCHAR(MAX)
DECLARE #SQL NVARCHAR(MAX)
IF OBJECT_ID('tempdb..#t1') IS NOT NULL DROP TABLE #t1
CREATE TABLE #t1 (col1 INT, col2 INT)
INSERT INTO #t1
SELECT 1, 1
UNION
SELECT 1, 2
SET #SQL = 'SET #myVar = (SELECT * FROM #t1 AS T FOR JSON AUTO);'
EXEC sp_executesql #SQL, N'#myVar VARCHAR(MAX) OUT', #myVar OUT
SELECT #myVar
You need to use a subquery:
SET #json = (SELECT TOP (1) getdate() AS [dateTime],suser_sname()AS [user] FOR JSON PATH);

SQL Server Is there a way to select columns from a given list

I have a list of columns that are dynamic then select the column in table that are in the list.
For example
Select (List of columns)
from tablename
Here is my code
SET NOCOUNT ON;
DECLARE #table TABLE(cols varchar(50));
DECLARE #tablename NVARCHAR(255);
DECLARE #tableid INT;
DECLARE #sSQL NVARCHAR(500);
SET #tableid = (SELECT DISTINCT TABLEID FROM faciltyShowedDetails WHERE layerid = #layerid);
SET #tablename = (SELECT dbo.FNC_Search_GetSearchTable(#tableid))
INSERT INTO #table(cols)
SELECT COLUMN_NAME
FROM faciltyShowedDetails
WHERE layerid = #layerid;
I want to select from the list of column in #table.
You would construct the query and use dynamic SQL. Assuming the "list" is really a comma-delimited list:
declare #sql nvarchar(max);
set #sql = 'select [cols] from tablename';
set #sql = replace(#sql, '[cols]', #cols);
exec sp_executesql #sql;
EDIT:
To get the columns from a table, you can use the trick:
declare #cols varchar(max);
select #cols = ', ' + columnname
from #table t;
You then have to remove the first comma (using stuff()) in the previous code.

How can I use a local variable in SELECT FROM?

I declared a variable #Obj and assign a complete table name 'ODS..Account' to it.
DECLARE #Obj VARCHAR(255)
Then I used it in a query immediately after FROM Clause. I perceive it is just a string, unable to act as a table object. So how can I fix the code to get it works? Cheers
INSERT Control.dbo.Consistency_Check
(Table_Name
,Schema_Name
,Id
,Incremental_DateTime_Column
)
SELECT
#Tab
,'ODS'
,Id
,SystemModstamp
FROM
#Obj )
You can use a local variable as a scalar value, not as a function. To do this, you need dynamic SQL:
declare #sql varchar(max);
select #sql = '
INSERT Control.dbo.Consistency_Check(Table_Name, Schema_Name, Id, Incremental_DateTime_Column)
SELECT ''#Tab'', 'ODS', Id, SystemModstamp
FROM #Tab
';
select #sql = replace(#sql, '#tab', #tab);
exec sp_executesql #sql;
Slightly different way of doing it with dynamic SQL:
DECLARE #Obj VARCHAR(255) = 'dbo.table'
DECLARE #SQL NVARCHAR(MAX) = ''
SET #SQL = #SQL +
'INSERT Control.dbo.Consistency_Check
(Table_Name
,Schema_Name
,Id
,Incremental_DateTime_Column
)
SELECT
#Tab
,''ODS''
,Id
,SystemModstamp
FROM
' + #Obj + ''
EXEC (#SQL)
You cannot. You probably want to use dynamic query. i.e. workout the SQL query string into a variable and exec using sp_executesql.
You may use the same variable name in the dynamic SQL but I changed it to #p_Tab for the example.
DECLARE #Tab int = 3
DECLARE #SQLString nvarchar(500)
DECLARE #ParmDefinition nvarchar(500) = N'#p_Tab int';
Declare #TableName nvarchar(100) = 'ODS..Account'
/* Build the SQL string dynamicly.*/
SET #SQLString = N'INSERT Control.dbo.Consistency_Check
(Table_Name
,Schema_Name
,Id
,Incremental_DateTime_Column
)
SELECT
#p_Tab
,''ODS''
,Id
,SystemModstamp
FROM
'+ #TableName
EXECUTE sp_executesql #SQLString, #ParmDefinition,
#p_Tab = #Tab
Further reference: https://msdn.microsoft.com/en-us/library/ms188001.aspx

how to assign results from exec to variable

How do I assign the results of an exec command to a variable. like the below, so when I do select #sql2 I get the result of the executed varchar sql.
declare #sql varchar(500)
declare #sql2 varchar(max)
set #sql = 'SELECT
PDB.OutletBrandID, OB.BrandName
FROM
ProductDistributionBrand PDB
INNER JOIN
[IND_roadchef].dbo.OutletBrands OB
ON
PDB.OutletBrandID = OB.OutletBrandID
FOR XML PATH(''ProductDistributionBrandDetail''),ROOT(''ProductDistributionBrandDetails''),TYPE'
--select #sql
set #sql2 = exec(#sql)
select #sql2
Use an output param:
declare #sql nvarchar(500)
declare #xml XML
set #sql = 'set #xml = (SELECT ..... FOR XML PATH(''ProductDistributionBrandDetail''),ROOT(''ProductDistributionBrandDetails''),TYPE)'
EXEC sp_executesql #sql, N'#xml XML output', #xml = #xml OUTPUT
select #xml
You can use Table Variables. Try like this,
DECLARE #sql TABLE (col1 VARCHAR(500))
DECLARE #sql2 VARCHAR(max)
SET #sql2 = 'SELECT
PDB.OutletBrandID, OB.BrandName
FROM
ProductDistributionBrand PDB
INNER JOIN
[IND_roadchef].dbo.OutletBrands OB
ON
PDB.OutletBrandID = OB.OutletBrandID
FOR XML PATH(''ProductDistributionBrandDetail''),ROOT(''ProductDistributionBrandDetails''),TYPE'
INSERT INTO #sql
EXEC (#sql2)
SELECT *
FROM #sql
Please see reference from this link it will show you how to use output parameters
https://support.microsoft.com/en-us/kb/262499

Insert results of SELECT Statement into SQL input Parameter

I have a comma delimited list of column names that I am casting to XML and then selecting. I would like to then insert these into the #selectedRows input parameter, which will be called in a stored procedure. How do you insert these multiple values into the #selectedRows parameter? Thanks!
Convert Comma Delimited List to XML and Select:
DECLARE #xml as xml,#string as varchar(1000),#delimiter as varchar(10)
SET #string='Column1,Column2,Column3,Column4,Column5'
SET #delimiter =','
SET #xml = cast(('<X>'+replace(#string,#delimiter ,'</X><X>')+'</X>') as xml)
SELECT N.value('.', 'varchar(25)') as value FROM #xml.nodes('X') as T(N)
This will be in stored procedure:
Select #selectedRows
from Test
where TestField > TestField
you do not need to split the comma delimited string of column names, but you would need to use dynamic sql for this something like this....
Declare #Sql NVarChar(Max);
Declare #string VarChar(1000) = 'Column1,Column2,Column3,Column4,Column5';
SET #Sql = N' SELECT ' + #string
+ N' From Test '
+ N' where TestField > TestField'
Exec sp_executesql #Sql

Resources