Get parameter from EXECUTE statement in SQL Server? - sql-server

I want to create procedures with dynamic query like this
set #x = #query + CAST(#year AS varchar(10)) + ' and ' + #attribute + #operator +''''+ #value+''''
execute (#x)
Now I want to get value from execute statement but
select * from execute(#x)
does not work! Please help me

You should declare a variable you will use to get the value from the dynamic query and use executesql to execute your query.
Something like:
declare #x int
declare #sql nvarchar(max) = N'SELECT #x = SomeColumn FROM SomeTable'
exec sp_executesql #sql, N'#x int out', #x out
select #x

Related

SQL Server Table Parameter without defining fields [duplicate]

I am trying to execute this query:
declare #tablename varchar(50)
set #tablename = 'test'
select * from #tablename
This produces the following error:
Msg 1087, Level 16, State 1, Line 5
Must declare the table variable "#tablename".
What's the right way to have the table name populated dynamically?
For static queries, like the one in your question, table names and column names need to be static.
For dynamic queries, you should generate the full SQL dynamically, and use sp_executesql to execute it.
Here is an example of a script used to compare data between the same tables of different databases:
Static query:
SELECT * FROM [DB_ONE].[dbo].[ACTY]
EXCEPT
SELECT * FROM [DB_TWO].[dbo].[ACTY]
Since I want to easily change the name of table and schema, I have created this dynamic query:
declare #schema sysname;
declare #table sysname;
declare #query nvarchar(max);
set #schema = 'dbo'
set #table = 'ACTY'
set #query = '
SELECT * FROM [DB_ONE].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table) + '
EXCEPT
SELECT * FROM [DB_TWO].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table);
EXEC sp_executesql #query
Since dynamic queries have many details that need to be considered and they are hard to maintain, I recommend that you read: The curse and blessings of dynamic SQL
Change your last statement to this:
EXEC('SELECT * FROM ' + #tablename)
This is how I do mine in a stored procedure. The first block will declare the variable, and set the table name based on the current year and month name, in this case TEST_2012OCTOBER. I then check if it exists in the database already, and remove if it does. Then the next block will use a SELECT INTO statement to create the table and populate it with records from another table with parameters.
--DECLARE TABLE NAME VARIABLE DYNAMICALLY
DECLARE #table_name varchar(max)
SET #table_name =
(SELECT 'TEST_'
+ DATENAME(YEAR,GETDATE())
+ UPPER(DATENAME(MONTH,GETDATE())) )
--DROP THE TABLE IF IT ALREADY EXISTS
IF EXISTS(SELECT name
FROM sysobjects
WHERE name = #table_name AND xtype = 'U')
BEGIN
EXEC('drop table ' + #table_name)
END
--CREATES TABLE FROM DYNAMIC VARIABLE AND INSERTS ROWS FROM ANOTHER TABLE
EXEC('SELECT * INTO ' + #table_name + ' FROM dbo.MASTER WHERE STATUS_CD = ''A''')
Use:
CREATE PROCEDURE [dbo].[GetByName]
#TableName NVARCHAR(100)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #sSQL nvarchar(500);
SELECT #sSQL = N'SELECT * FROM' + QUOTENAME(#TableName);
EXEC sp_executesql #sSQL
END
You can't use a table name for a variable. You'd have to do this instead:
DECLARE #sqlCommand varchar(1000)
SET #sqlCommand = 'SELECT * from yourtable'
EXEC (#sqlCommand)
You'll need to generate the SQL content dynamically:
declare #tablename varchar(50)
set #tablename = 'test'
declare #sql varchar(500)
set #sql = 'select * from ' + #tablename
exec (#sql)
Use sp_executesql to execute any SQL, e.g.
DECLARE #tbl sysname,
#sql nvarchar(4000),
#params nvarchar(4000),
#count int
DECLARE tblcur CURSOR STATIC LOCAL FOR
SELECT object_name(id) FROM syscolumns WHERE name = 'LastUpdated'
ORDER BY 1
OPEN tblcur
WHILE 1 = 1
BEGIN
FETCH tblcur INTO #tbl
IF ##fetch_status <> 0
BREAK
SELECT #sql =
N' SELECT #cnt = COUNT(*) FROM dbo.' + quotename(#tbl) +
N' WHERE LastUpdated BETWEEN #fromdate AND ' +
N' coalesce(#todate, ''99991231'')'
SELECT #params = N'#fromdate datetime, ' +
N'#todate datetime = NULL, ' +
N'#cnt int OUTPUT'
EXEC sp_executesql #sql, #params, '20060101', #cnt = #count OUTPUT
PRINT #tbl + ': ' + convert(varchar(10), #count) + ' modified rows.'
END
DEALLOCATE tblcur
You need to use the SQL Server dynamic SQL:
DECLARE #table NVARCHAR(128),
#sql NVARCHAR(MAX);
SET #table = N'tableName';
SET #sql = N'SELECT * FROM ' + #table;
Use EXEC to execute any SQL:
EXEC (#sql)
Use EXEC sp_executesql to execute any SQL:
EXEC sp_executesql #sql;
Use EXECUTE sp_executesql to execute any SQL:
EXECUTE sp_executesql #sql
Declare #tablename varchar(50)
set #tablename = 'Your table Name'
EXEC('select * from ' + #tablename)
Also, you can use this...
DECLARE #SeqID varchar(150);
DECLARE #TableName varchar(150);
SET #TableName = (Select TableName from Table);
SET #SeqID = 'SELECT NEXT VALUE FOR ' + #TableName + '_Data'
exec (#SeqID)
Declare #fs_e int, #C_Tables CURSOR, #Table varchar(50)
SET #C_Tables = CURSOR FOR
select name from sysobjects where OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name like 'TR_%'
OPEN #C_Tables
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
WHILE ( #fs_e <> -1)
BEGIN
exec('Select * from ' + #Table)
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
END

SQL set variable as the result of a query in a stored procedure

I am creating a stored procedure with a cursor and I need to store the quantity of a column into a variable.
SQL says that it cannot convert nvarchar into int
I have tried to use CONVERT, CAST and EXEC but couldn't make it work.
How can I solve this ?
DECLARE #FieldName nvarchar(255);
DECLARE #RequestCode Nvarchar(50);
DECLARE #ReqSQLQuantity nvarchar(max);
DECLARE #Quantity int;
Select #ReqSQLQuantity = concat('select count(*) From (select distinct [', #FieldName , '] from [report_' , #RequestCode , ']) as number')
Set #Quantity = (#ReqSQLQuantity)
Select #Quantity
Another a bit safer option would be to use sp_executesql stored procedure something like this....
DECLARE #FieldName nvarchar(255);
DECLARE #RequestCode Nvarchar(50);
DECLARE #ReqSQLQuantity nvarchar(max);
DECLARE #Quantity int, #tableName SYSNAME;
SET #tableName = N'report_' + #RequestCode
Select #ReqSQLQuantity = N' select #Quantity = count(*) '
+ N' From (select distinct ' + QUOTENAME(#FieldName)
+ N' from ' + QUOTENAME(#tableName) + N' ) as number'
Exec sp_executesql #ReqSQLQuantity
,N'#Quantity INT OUTPUT'
,#Quantity OUTPUT
Select #Quantity
Set #Quantite = (#ReqSQLQuantite)
This is not an evaluation, is an implicit conversion. From NVARCHAR to INT, and you are trying to convert a SQL query text into an INT, hence the error.
Also, you are assuming that results are the same as return values and can be assigned to variables. This is incorrect, SQL execution results are sent to the client. To capture a result, you must use a SELECT assign: SELECT #value =.... Trying to run #variable = EXEC(...) is not the same thing. Think at SELECT results the same way as a print in an app: a print sends some text to the console. If you run some pseudo-code like x = print('foo') then 'foo' was sent to the console, and x contains the value returned by print (whatever that is). Same with this pseudo-SQL, #x = EXEC('SELECT foo') will send foo to the client, and #x will some numeric value which is the value returned by EXEC (in a correct example one would have to use explicit RETURN statement to set it).
Overall, the code as posted has absolutely no need for capturing the value and returning it, it can simply execute the dynamic SQL and let the result be returned to client:
SET #sql = concat(N'SELECT count(*) FROM (SELECT ... FROM ...)');
exec sp_executesql #sql;

Multiplying values in dynamic SQL

Using dynamic SQL I want to insert two columns into a table. The second column will be calculated using two parameters that are passed in from another stored procedure. I know I can do the below using sp_execute but wondered if I could do similar using just EXEC
DECLARE #vsql nvarchar(max)
DECLARE #p1 numeric
SET #p1 = 5
SET #vsql = ' Select PORTFOLIO_CODE, (#p1 * #p1) as leverage
INTO greg
from ssc.slh
select * from greg'
Exec sp_executesql
#stmt = #vsql,
#params = N'#p1 as numeric',
#p1 = #p1
Can I do this using Exec? The below doesn't seem to work does the multiply operand need to be a sting literal?
DECLARE #vsql nvarchar(max)
DECLARE #p1 numeric
SET #p1 = 5
SET #vsql = ' Select PORTFOLIO_CODE, (' + #p1 * #p1 + ') as leverage
INTO greg
from ssc.slh
select * from greg'
Exec sp_executesql
Why do you need dynamic SQL? You can just use the variable in your query output
DECLARE #p1 numeric = 5;
Select
PORTFOLIO_CODE, (#p1 * #p1) as leverage
from ssc.slh
EDIT:
For dynamic column mapping.
Both #p1 and #p2 are column names you want to multiply?
DECLARE
#p1 nvarchar(200) = 'myFirstColumnName',
#p2 nvarchar(200) = 'mySecondColumnName',
DECLARE #vsql nvarchar(max) = 'SELECT PORTFOLIO_CODE, ([' + #p1 +'] * ['+ #p2 + ']) leverage from ssc.slh';
PRINT #vsql;
Exec sp_executesql #vsql;

T-SQL SELECT STATEMENT AS A VARIABLE AND PUT RESULT TO ANOTHER VARIABLE

This is the last part of my function:
SET #query = (N'SELECT [' +#outColumn+'] FROM [Production].[dbo].[v_time] WHERE textile LIKE '''+#outTextile+'''')
I tried like this: (also I tried with 'exec sp_executesql(#query)' and it doesn't work)
SET #output = (#query)
RETURN #output
And as result I get is the exact SQL query I wanted. But, how to RUN (execute) #query and its result (in this case it is a decimal number) put in variable #output and return??
Try something like.....
Declare #query NVarchar(MAX)
, #outColumn SYSNAME
, #Out DECIMAL(10,2)
SET #query = N' SELECT TOP 1 #Out = ' +QUOTENAME(#outColumn)
+ N' FROM [Production].[dbo].[v_time] '
+ N' WHERE textile LIKE ''%'' + #outTextile + ''%'''
Exec sp_executesql #query
,N'#outTextile VARCHAR(50) , #Out DECIMAL(10,2) OUTPUT'
,#outTextile
,#Out OUTPUT

how to set insert string values in sql server?

I have this query in sql server
DECLARE #SQL NVARCHAR(MAX),#X NVARCHAR(MAX)
SET #X = 'val1,val2'
SET #SQL = 'INSERT INTO [Persons] VALUES (' + #X + ')'
print (#SQL)
exec (#SQL)
But i don't know how to set #x value by the right way ?
You need to add escaped quotes:
SET #X = '''val1'',''val2'''
To make #X contain 'val1','val2'
You have to DECLARE every parameter.
DECLARE #SQL NVARCHAR(MAX)
DECLARE #X NVARCHAR(MAX)
SET #X = '''val1'',''val2'''
SET #SQL = 'INSERT INTO [Persons] VALUES (' + #X + ')'
print (#SQL)
exec (#SQL)
see from this link use split function,
How do I split a string so I can access item x?
then
Declare #ColNames VARCHAR(1000)='val1,val2'
INSERT INTO [Persons]
select item from dbo.SplitString(#ColNames,',')
Here's a SQL Fiddle.
If Val1 and Val2 are string fields, you have to escape single quotes around string values as follows.
DECLARE #SQL NVARCHAR(MAX)
DECLARE #X NVARCHAR(MAX)
SET #X = '''val1'',''val2'''
SET #SQL = 'INSERT INTO [Persons] VALUES (' + #X + ')'
print (#SQL)
exec (#SQL)

Resources