I am working on some pretty long and complicated procedure in T-SQL where I need to use quite a lot variables in queries.
I got stuck on something like this:
SELECT #TableSQL = 'SELECT '
+ #columnsForInsert
+ '= COALESCE(#columnsForInsert
+ ''], ['', '''')
+ name
FROM MIGRATION_DICTIONARIES.dbo.' + #TableName + '_COLUMNS '
EXEC sp_executesql #TableSQL
PRINT #columnsForInsert
As you can see I try to concatenate all the rows from some temporary table into a single line and then assign it to #columnsForInsert variable. However, when I run this string by sp_executesql it goes to the scope where #columnsForInsert is not visible.
Do you have guys any idea how to get this running?
In other words. I have something like
SELECT #columnsForInsert = COALESCE(#columnsForInsert + '], [', '') + name
FROM MIGRATION_DICTIONARIES.dbo.Foobar_COLUMNS
This works fine in my procedure. However, in the final version Foobar will be in a variable so simple putting #tableName there does not work. How can I achieve this?
I am using Microsoft SQL Server 2012
Here is an example of how to capture output from sp_executesql
http://support.microsoft.com/kb/262499
Although I have never done it, it implies that the below syntax might work to retrieve your variable value from your sp_executesql (assuming all the quotes are in the right place and your syntax is correct)
DECLARE #columnsForInsertOUT VARCHAR(400)
DECLARE #columnsForInsert VARCHAR(400)
DECLARE #ParmDefinition VARCHAR(50)
DECLARE #TableSQL VARCHAR(200)
DECLARE #TableName VARCHAR(200)
SELECT #TableSQL = 'SELECT #columnsForInsertOUT = COALESCE(#columnsForInsertOUT'
+ ''], ['', '''')
+ name
FROM MIGRATION_DICTIONARIES.dbo.' + #TableName + '_COLUMNS '
SET #ParmDefinition = '#columnsForInsertOUT varchar(400) OUTPUT'
EXECUTE sp_executesql
#TableSQL,
#ParmDefinition,
#columnsForInsertOUT=#columnsForInsert OUTPUT
SELECT #columnsForInsert
Related
For the last couple days I am pulling my hair out because of a problem I have.
In a stored procedure, I want to use the column name as parameter to update a value in the table.
I have the following code
ALTER PROCEDURE [dbo].[Item_Update_Single]
#Id nvarchar(15),
#ColumnName nvarchar(80),
#NewValue nvarchar(80)
AS
DECLARE #sql NVARCHAR(MAX)
SET #sql = N'UPDATE [Item] SET [' + QUOTENAME(#ColumnName) + ']' + '= ' + QUOTENAME(#NewValue) +' WHERE [Id] = ' + #Id
PRINT #sql
The stored procedure is running fine, no errors, but the table is not updated. If I run the #SQL string in query window, the data is updated.
I am a sort of newbie but what did I do wrong here?
You never execute your dynamic statement. Your use of QUOTENAME is also wrong. '[' + QUOTENAME(#ColumnName) + ']' would result in [[ColumnName]] and QUOTENAME(#NewValue) would refer to a column with the name of what ever value is in #NewValue, not a string literal. You should be parametrising the statement and properly injecting the dynamic object:
ALTER PROCEDURE [dbo].[Item_Update_Single] #Id int, --Guess this is actually an int
#ColumnName sysname, --Corrected data type
#NewValue nvarchar(80) --I assume this is correct
AS
BEGIN
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'UPDATE dbo.[Item] SET ' + QUOTENAME(#ColumnName) + ' = #NewValue WHERE [Id] = #ID;'
EXEC sys.sp_executesql #SQL, N'#NewValue nvarchar(80),#Id int', #NewValue, #ID;
END
This, however, seems like an XY Problem. Solutions like this are almost always a bad idea and often infer a significant design flaw.
Is there a way to do something like this? People is the name of the table.
declare #placeholder varchar(20) = 'People'
select * from #placeholder
Or something like this where the table name is People_Backup.
declare #placeholder varchar(20) = '_Backup'
select * from People#placeholder
And is there a way to add in dynamic sql the value of a variable?
something like this:
declare #placeholder nvarchar(20) = 'people'
declare #name nvarchar(30) = 'antony'
declare #query nvarchar(1000) = 'select * from ' + #placeholder + ' where
first_name=' + #name
exec sp_executesql #query
I mean: without do this
exec sp_executesql #query, N'#name varchar(30)', #name
Thank you for the answers.
Not without dynamic SQL.
Parameters in SQL are placeholders for data, and can't be used as placeholders for anything else (which includes commands such as select, update etc' and identifiers such as database name, schema name, table name, column name etc').
The only way to parameterize table names is to use dynamic SQL - meaning you must build a string containing the SQL you want to execute, and then execute it.
Beware - dynamic SQL might be an open door for SQL injection attacks - so you must do it wisely - here are some ground rules:
Always white-list your identifiers (using system tables or views such as sys.Tables or Information_schema.Columns)
Always use sysname as the datatype for identifiers.
The sysname data type is used for table columns, variables, and stored procedure parameters that store object names. The exact definition of sysname is related to the rules for identifiers. Therefore, it can vary between instances of SQL Server.
Never pass SQL commands or clauses in parameters - set #placeholder = 'select a, b, c' or set #placeholder = 'where x = y' is a security hazard!
Always use parameters for data. Never concatenate parameters into your sql string: set #sql = 'select * from table where x = '+ #x is a security hazard. Always create your dynamic SQL to use parameters as parameters: set #sql = 'select * from table where x = #x'
Always use sp_executeSql to execute your dynamic SQL statement, not EXEC(#SQL).
For more information, read Kimberly Tripp's EXEC and sp_executesql – how are they different?
Always wrap identifiers with QUOTENAME() to ensure correct query even when identifiers include chars like white-spaces
To recap - a safe version of what you are asking for (with an additional dynamic where clause to illustrate the other points) is something like this:
#DECLARE #TableName sysname = 'People',
#ColumnName sysname = 'FirstName'
#Search varchar(10) = 'Zohar';
IF EXISTS(
SELECT 1
FROM Information_Schema.Columns
WHERE TABLE_NAME = #TableName
AND COLUMN_NAME = #ColumnName
)
BEGIN
DECLARE #Sql nvarchar(4000) =
'SELECT * FROM +' QUOTENAME(#TableName) +' WHERE '+ QUOTENAME(#ColumnName) +' LIKE ''%''+ #Search +''%'';'
EXEC sp_executesql #Sql, N'#Search varchar(10)', #Search
END
-- you might want to raise an error if not
To answer your question after edited directly:
I mean: without do this exec sp_executesql #query, N'#name varchar(30)', #name
Yes, you can do it without using sp_executeSql, but it's dangerous - it will enable an attacker to use something like '';DROP TABLE People;-- as the value of #name, so that when you execute the sql, your People table will be dropped.
To do that, you will need to wrap the #name with ' -
declare #placeholder nvarchar(20) = 'people'
declare #name nvarchar(30) = 'antony'
declare #query nvarchar(1000) = 'select * from ' + QUOTENAME(#placeholder) + ' where
first_name=''' + #name +''''
exec(#query)
I mean: without do this exec sp_executesql #query, N'#name varchar(30)', #name
Yes, you can do that as
--Use MAX instead of 1000
DECLARE #SQL nvarchar(MAX) = N'SELECT * FROM ' + #placeholder + ' WHERE first_name = '''+#name +'''';
EXECUTE sp_executesql #SQL;
create procedure sp_First
#columnname varchar
AS
begin
select #columnname from Table_1
end
exec sp_First 'sname'
My requirement is to pass column names as input parameters.
I tried like that but it gave wrong output.
So Help me
You can do this in a couple of ways.
One, is to build up the query yourself and execute it.
SET #sql = 'SELECT ' + #columnName + ' FROM yourTable'
sp_executesql #sql
If you opt for that method, be very certain to santise your input. Even if you know your application will only give 'real' column names, what if some-one finds a crack in your security and is able to execute the SP directly? Then they can execute just about anything they like. With dynamic SQL, always, always, validate the parameters.
Alternatively, you can write a CASE statement...
SELECT
CASE #columnName
WHEN 'Col1' THEN Col1
WHEN 'Col2' THEN Col2
ELSE NULL
END as selectedColumn
FROM
yourTable
This is a bit more long winded, but a whole lot more secure.
No. That would just select the parameter value. You would need to use dynamic sql.
In your procedure you would have the following:
DECLARE #sql nvarchar(max) = 'SELECT ' + #columnname + ' FROM Table_1';
exec sp_executesql #sql, N''
Try using dynamic SQL:
create procedure sp_First #columnname varchar
AS
begin
declare #sql nvarchar(4000);
set #sql='select ['+#columnname+'] from Table_1';
exec sp_executesql #sql
end
go
exec sp_First 'sname'
go
This is not possible. Either use dynamic SQL (dangerous) or a gigantic case expression (slow).
Create PROCEDURE USP_S_NameAvilability
(#Value VARCHAR(50)=null,
#TableName VARCHAR(50)=null,
#ColumnName VARCHAR(50)=null)
AS
BEGIN
DECLARE #cmd AS NVARCHAR(max)
SET #Value = ''''+#Value+ ''''
SET #cmd = N'SELECT * FROM ' + #TableName + ' WHERE ' + #ColumnName + ' = ' + #Value
EXEC(#cmd)
END
As i have tried one the answer, it is getting executed successfully but while running its not giving correct output, the above works well
You can pass the column name but you cannot use it in a sql statemnt like
Select #Columnname From Table
One could build a dynamic sql string and execute it like EXEC (#SQL)
For more information see this answer on dynamic sql.
Dynamic SQL Pros and Cons
As mentioned by MatBailie
This is much more safe since it is not a dynamic query and ther are lesser chances of sql injection . I Added one situation where you even want the where clause to be dynamic . XX YY are Columns names
CREATE PROCEDURE [dbo].[DASH_getTP_under_TP]
(
#fromColumnName varchar(10) ,
#toColumnName varchar(10) ,
#ID varchar(10)
)
as
begin
-- this is the column required for where clause
declare #colname varchar(50)
set #colname=case #fromUserType
when 'XX' then 'XX'
when 'YY' then 'YY'
end
select SelectedColumnId from (
select
case #toColumnName
when 'XX' then tablename.XX
when 'YY' then tablename.YY
end as SelectedColumnId,
From tablename
where
(case #fromUserType
when 'XX' then XX
when 'YY' then YY
end)= ISNULL(#ID , #colname)
) as tbl1 group by SelectedColumnId
end
First Run;
CREATE PROCEDURE sp_First #columnname NVARCHAR(128)--128 = SQL Server Maximum Column Name Length
AS
BEGIN
DECLARE #query NVARCHAR(MAX)
SET #query = 'SELECT ' + #columnname + ' FROM Table_1'
EXEC(#query)
END
Second Run;
EXEC sp_First 'COLUMN_Name'
Please Try with this.
I hope it will work for you.
Create Procedure Test
(
#Table VARCHAR(500),
#Column VARCHAR(100),
#Value VARCHAR(300)
)
AS
BEGIN
DECLARE #sql nvarchar(1000)
SET #sql = 'SELECT * FROM ' + #Table + ' WHERE ' + #Column + ' = ' + #Value
--SELECT #sql
exec (#sql)
END
-----execution----
/** Exec Test Products,IsDeposit,1 **/
I want to create a procedure that can execute any select in database and has table name and column names and where clause as input parameters
how can I develop that?
As an exam exercise, it's ok, but never do something like this in a real environment because of the SQL Injection danger.
CREATE PROCEDURE QueryExecution (
#columns varchar(200),
#tableName varchar(50),
#conditions varchar(200))
AS
BEGIN
declare #query nvarchar(max);
set #query = 'SELECT ' + #columns + ' FROM ' + #tableName + ' WHERE ' + #conditions
exec sp_executesql #query
END
Then call it like this:
exec QueryExecution 'Id, Description', 'MyTable', 'Id > 5 AND Description LIKE ''%some text%'''
Note: if you need single quotes in your string, you must escape them by doubling them, like you can see in the LIKE clause.
exec sp_executesql N'SELECT (STUFF (( SELECT '',''+ NAME from Project WHERE ProjectTypeID=1 and OutputHierarchyID IN (SELECT DISTINCT HierarchyID from HierarchyNode'+ #TextVal +''''
+ N')FOR XML PATH('''')), 1, 1, ''''))AS INDUSTRIES',
N'#Industries NVARCHAR(100) output', #Industries output;
I am getting error
Incorrect syntax near '+'.
You have extra single quotes. Try this
exec sp_executesql N'SELECT (STUFF (( SELECT '',''+ NAME from Project WHERE ProjectTypeID=1 and OutputHierarchyID IN (SELECT DISTINCT HierarchyID from HierarchyNode'+ #TextVal +''
+ N')FOR XML PATH('''')), 1, 1, ''''))AS INDUSTRIES',
N'#Industries NVARCHAR(100) output', #Industries output;
Also it is good pratice to assign dynamic query into a variable and use that varialbe for execution
You can't have an expression in the parameter to any procedure, including sp_executesql (this means you can't do things there like concatenate strings). Try the following, which also allows you to debug the statement in a more simple way (I'm not convinced your query is right, because I don't know why you want to add ' after #TextVal, which I assume is some table suffix):
DECLARE #sql NVARCHAR(MAX), #Industries NVARCHAR(100);
SET #sql = N'SELECT #Industries = STUFF((SELECT '','' + NAME
from Project WHERE ProjectTypeID = 1
and OutputHierarchyID IN
(
SELECT DISTINCT HierarchyID from HierarchyNode' + #TextVal + '
) FOR XML PATH('''')), 1, 1, '''');';
PRINT #sql;
--EXEC sp_executesql #sql, N'#Industries NVARCHAR(100) output', #Industries output;
Though I think this version will be slightly more efficient:
DECLARE #sql NVARCHAR(MAX), #Industries NVARCHAR(100);
SET #sql = N'SELECT #Industries = STUFF((SELECT '','' + NAME
from Project AS p WHERE ProjectTypeID = 1
AND EXISTS
(
SELECT 1 from HierarchyNode' + #TextVal + '
WHERE HierarchyID = p.OutputHierarchyID
) FOR XML PATH('''')), 1, 1, '''');';
PRINT #sql;
--EXEC sp_executesql #sql, N'#Industries NVARCHAR(100) output', #Industries output;
You can inspect the statement and be sure it's correct instead of just blindly throwing it at SQL Server and trying to figure out what the error messages might mean. If you copy and paste the output into the top pane, the error message will point to a line number that you can actually see and will make it easier to troubleshoot your syntax. When you believe it's producing correct output, comment the PRINT and uncomment the EXEC.
If you think the +''''+ after #TextVal is necessary, please tell us the value of #TextVal and the name of the table you expect that query to run against.