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)
Related
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
I am getting an error running the code below. I believe it as to do with the number of single quotes used.
How can I set a variable inside OPENQUERY command?
#declare #myStr varchar(6)
set #myStr = 'Test1'
SELECT *
FROM OPENQUERY("192.168.1.1",'SET FMTONLY OFF; EXEC spNewTest #Param1 = ''+ #myStr +''')
Click to see the error message
Regards,
Elio Fernandes
If you want to create a single quote within a string you have to put in two single quotes. For example:
'''this is a string''' would be a string containing the following:
'this is a string'
So for your problem, you have to change your code to this:
#declare #myStr varchar(6)
set #myStr = 'Test1'
SELECT *
FROM OPENQUERY("192.168.1.1",'SET FMTONLY OFF; EXEC spNewTest #Param1 = '''+ #myStr +'''')
I just found the answer for my question, so I thought sharing it with you.
DECLARE #QUERY VARCHAR(MAX)
DECLARE #TSQL VARCHAR(100)
DECLARE #SP VARCHAR(50)
DECLARE #PARAMETERS VARCHAR(MAX)
DECLARE #PARAM1 VARCHAR(50)
DECLARE #PARAM2 VARCHAR(50)
SET #TSQL = N'SELECT * FROM OPENQUERY([192.168.1.1], ''SET FMTONLY OFF; '
SET #SP = 'EXEC spNewTest '
SET #PARAM1 = '#Type='''+ QUOTENAME('Test','''') + ''''
SET #PARAM2 = '#Year='''+ QUOTENAME('2016','''') + ''''
SET #PARAMETERS = #PARAM1 + ', ' + #PARAM2
SET #QUERY = #TSQL + #SP + #PARAMETERS + ''')'
EXECUTE (#QUERY)
Thanks
The following code return not more than 8000 character in SQL server 2012. Is there a possible method to print more than 8000 characters
DECLARE #SQL VARCHAR(MAX)
SET #SQL = ''
SELECT #SQL = #SQL + CAST('SELECT * FROM ' + TableName AS VARCHAR(MAX))
FROM Table1
PRINT(#SQL)
Try:
PRINT SUBSTRING(#SQL,0,8000)
PRINT SUBSTRING(#SQL,8001,8000)
PRINT SUBSTRING(#SQL,16001,8000)
etc
I believe the problem lies with how you insert the data. I was able to get 8001 characters returned with your code with the following table creation and insert.
Drop Table #Test
Create Table #Test (Test Varchar(Max))
Insert #Test Values (Convert(Varchar(Max),Space(7999)) + 'xy')
Select * From #Test
DECLARE #TableName VARCHAR(MAX) = '#Test'
DECLARE #SQL VARCHAR(MAX) SET #SQL = ''
SELECT #SQL = #SQL + CAST('SELECT Test FROM ' + #TableName AS VARCHAR(MAX)) FROM #Test
PRINT(#SQL)
Note how the value is cast as varchar(max) on insertion.
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
I am wondering why I cannot use variable column name like that:
declare #a as varchar;
set #a='TEST'
select #a from x;
Thank you
You can't do it because SQL is compiled before it knows what the value of #a is (I'm assuming in reality you would want #a to be some parameter and not hard coded like in your example).
Instead you can do this:
declare #a as varchar;
set #a='TEST'
declare #sql nvarchar(max)
set #sql = 'select [' + replace(#a, '''', '''''') + '] from x'
exec sp_executesql #sql
But be careful, this is a security vulnerability (sql-injection attacks) so shouldn't be done if you can't trust or well clean #a.
Because it is not allowed.
Insted of this you could use dynamic sql query:
declare #a as varchar;
set #a='TEST'
exec ('select ' + #a + ' from x')
Because the column names are resolved at compile time not at run time for the SQL statement.
use sp_executesql for this
Example
SET #SQLString = N'SELECT *
FROM table1
WHERE timet = #time and items in (#item)';
DECLARE #SQLString nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
SET #ParmDefinition = N'#time timestamp,
#item varchar(max) ';
EXECUTE sp_executesql
#SQLString
,#ParmDefinition
,#time = '2010-04-26 17:15:05.667'
,#item = '''Item1'',''Item2'',''Item3'',''Item4'''
;
If there are not too many columns to chose, how about a CASE WHEN statement?
DECLARE #ColName VARCHAR(50) = 'Test1'
SELECT [Foo], [Bar],
CASE
WHEN #ColName = 'Test1' THEN [Test1]
WHEN #ColName = 'Test2' THEN [Test2]
WHEN #ColName = 'Test3' THEN [Test3]
WHEN #ColName = 'Test4' THEN [Test4]
ELSE [TestDefault]
END [TestResult]
FROM [TableName];
This avoids using any EXEC.