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.
Related
Using SQL Server 2012, I've found that trying to build up a string based on an nvarchar(max) column in a table doesn't seem to work correctly. It seems to overwrite, instead of append. Arbitrary Example:
DECLARE #sql nvarchar(max);
SELECT #sql = N'';
SELECT #sql += [definition] + N'
GO
'
FROM sys.sql_modules
WHERE OBJECT_NAME(object_id) LIKE 'dt%'
ORDER BY OBJECT_NAME(object_id);
PRINT #sql;
This SHOULD print out all the SQL module definitions for all the various dt_ tables in the database, separated by GO, as a script that could then be run. However... this prints out only the LAST module definition, not the sum of all of them. It's behaving as if the "+=" were just an "=".
If you change it just slightly... cast [definition] to an nvarchar(4000) for example, it suddenly works as expected. Also, if you choose any other column that is NOT an nvarchar(max) or varchar(max) type, it works as expected. Example:
DECLARE #sql nvarchar(max);
SELECT #sql = N'';
SELECT #sql += CAST([definition] AS nvarchar(4000)) + '
GO
'
FROM sys.sql_modules
WHERE OBJECT_NAME(object_id) LIKE 'dt%'
ORDER BY OBJECT_NAME(object_id);
PRINT #sql;
Is this a known bug? Or is this working as expected? Am I doing something wrong? Is there any way for me to make this work correctly? I've tried a dozen different things, including ensuring every expression in the concatenation is the same nvarchar(max) type, including the string literal.
NOTE: The example is just an example that shows the problem, and not exactly what I'm trying to do in real life. If your database doesn't have the "dt*" tables defined, you can change the WHERE clause to specify any group of tables or stored procedures in any database you want, you'll get the same result... only the last one shows up in the #sql string, as if you just did "=" instead of "+=". Also, explicitly stating "#sql = #sql + " behaves the same way... works correctly with every string type EXCEPT nvarchar(max) or varchar(max).
I've verified that none of the [definition] values is NULL as well, so there are no NULL shenanigans going on.
The += operator only applies to numeric data types in SQL Server. Microsoft documentation here
For string concatenation, you need to write the assignment and concatenation separately.
DECLARE #sql nvarchar(max);
SELECT #sql = N'';
SELECT #sql = #sql + [definition] + N'
GO
'
FROM sys.sql_modules
WHERE OBJECT_NAME(object_id) LIKE 'dt%'
ORDER BY OBJECT_NAME(object_id);
PRINT #sql;
Also, if you are running this query in Management Studio, keep in mind that there is a limit to the size of the data that it will return (including in a print statement). So if the definitions of your modules exceed this limit, they will be truncated in the output.
To add on to #HABO's comment, the behavior of aggregate string concatenation is undefined and results are plan dependent. Use FOR XML to provide deterministic results and honor the ORDER BY clause:
DECLARE #sql nvarchar(max);
SET #sql =
(SELECT [definition] + N'
GO
'
FROM sys.sql_modules
WHERE OBJECT_NAME(object_id) LIKE 'dt%'
ORDER BY OBJECT_NAME(object_id)
FOR XML PATH(''), TYPE).value('(./text())[1]', 'nvarchar(MAX)');
PRINT #sql; --SSMS will truncate long strings
It works as expected:
DECLARE #sql nvarchar(max);
SELECT #sql =COALESCE(#sql + N' GO ','')+[definition]
FROM sys.sql_modules
Print #sql;
The following code demonstrates taking a column value from a set of ordered rows and, using for xml, creating an aggregated string with separators, including line breaks, between values.
-- Carriage return and linefeed characters.
declare #CRLF as NVarChar(16) = NChar( 13 ) + NChar( 10 );
-- Carriage return and linefeed characters XML encoded.
declare #EncodedCRLF as NVarChar(16) = N'
';
-- Separator to insert between source rows in the accumulated string.
declare #Separator as NVarChar(64) = ';' + #EncodedCRLF + 'go;' + #EncodedCRLF + 'do something with ';
-- Characters in #Separator to remove from the first element in #Result .
declare #SkipCount as Int = 4 + 2 * Len( #EncodedCRLF );
-- The result.
declare #Result as NVarChar( max ) = '';
-- Do it.
select #Result =
Replace(
Stuff(
-- Specify the sorting order of the XML elements in the following select statement.
( select #Separator + name from sys.tables order by name desc for XML path(''), type).value('.[1]', 'VarChar(max)' ),
1, #SkipCount, '' ),
#EncodedCRLF, #CRLF );
-- Output the result.
select #Result as [Result];
-- Output the result with line breaks shown.
print #Result; -- Switch to Messages tab in SSMS to see result.
I´m pretty sure the PRINT command is the reason for the troubles.
When I try:
DECLARE #SQL NVARCHAR(MAX) = N'';
SELECT #sql += SUBSTRING( [definition], 1, 100 ) + CHAR(13) + CHAR(10) + 'GO' + CHAR(13) + CHAR(10)
FROM SYS.SQL_MODULES
PRINT #sql;
I get all my procedures (the first 100 chars ...). So it seems to be a limitation to the PRINT command.
Second try, another database, without "substring":
DECLARE #SQL NVARCHAR(MAX) = N'';
SELECT #sql += [definition] + CHAR(13) + CHAR(10) + 'GO' + CHAR(13) + CHAR(10)
FROM SYS.SQL_MODULES
PRINT #sql;
Now I got 1,5 procedures: The 1st one complete, the second stopped in the middle of on line in the proc. There is a limit in PRINT
Third try, to proof my assumption:
DECLARE #SQL NVARCHAR(MAX) = N'';
SELECT #sql += [definition] + 'GO' FROM SYS.SQL_MODULES
PRINT #sql;
Now I got one line of code more! So for me, this is the proof, that PRINT has somehow a limit.
A last attempt:
DECLARE #SQL NVARCHAR(MAX) = N'';
SELECT #sql += [definition] + N'GO' FROM SYS.SQL_MODULES
PRINT SUBSTRING(#SQL,1,4000)
PRINT SUBSTRING(#SQL,4001,4000)
The result: Now I got more then 2 procedures, although there now is a line break after 4K, this may occur on ... bad places.
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 **/
When I run this code I get no errors:
SELECT * INTO GT_Item
FROM OPENQUERY(PLPPROD_LS,
'SELECT
ITEM_CODE AS GT_ITEM_CODE, ITEMC_CODE, ITEM_DESC,
VALID_CODE_PROD,
CASE
WHEN ITEMC_CODE LIKE ''WIP%''
THEN ''WIP-''||(SELECT MAX(JOBOP.JOB_NO)||''-''||MAX(OPCLASS_CODE) FROM REC INNER JOIN JOBOP ON JOBOP.JOBOP_ID = REC.JOBOP_ID WHERE REC.ITEM_CODE = ITEM.ITEM_CODE)
ELSE ITEM_CODE
END AS GALAXY_ITEM_CODE
FROM ITEM')
However, when I set #sql NVARCHAR(2000) equal to the string in the openquery and try to run
DECLARE #SQL NVARCHAR(MAX) = N'SELECT
ITEM_CODE AS GT_ITEM_CODE, ITEMC_CODE, ITEM_DESC,
VALID_CODE_PROD,
CASE
WHEN ITEMC_CODE LIKE ''WIP%''
THEN ''WIP-''||(SELECT MAX(JOBOP.JOB_NO)||''-''||MAX(OPCLASS_CODE) FROM REC INNER JOIN JOBOP ON JOBOP.JOBOP_ID = REC.JOBOP_ID WHERE REC.ITEM_CODE = ITEM.ITEM_CODE)
ELSE ITEM_CODE
END AS GALAXY_ITEM_CODE
FROM ITEM'
EXEC('SELECT * INTO GT_Item FROM OPENQUERY(PLPPROD_LS, ''' + #SQL + ''')' )
I get an invalid syntax error pointing to the ''WIP%'' section of the string. Further, if I change that condition to another one (e.g. ITEMC_CODE IN ('WIP_PRT','WIP_LAM')), I get the same error at the same section.
Why am I getting the error when I run the code one way and not the other? My other queries in the same stored procedure are executed the second way without issue.
The linked server is an oracle 11 server. I have not simplified the query, since the error message indicates that it is a syntax error.
EDIT:
To be clear:
EXEC('SELECT * INTO GT_Item FROM OPENQUERY(PLPPROD_LS, ''' + #SQL + ''')' ) works when #SQL is set to many other things, including but not limited to SELECT ITEM_CODE AS GT_ITEM_CODE, ITEMC_CODE, ITEM_DESC, VALID_CODE_PROD FROM ITEM. However, the listed String above with the CASE statement will only execute if I do not use EXEC, but rather write it in as shown.
EDIT2: Found solution, need to double escape the ' in the #SQL string. Don't know why that is, but replacing '' with '''' let EXEC run, and did not leave extra ' in my final table.
Correct way do not rely on concatenation and multiple '' and use parameters instead:
DECLARE #query NVARCHAR(MAX) = N'SELECT * INTO GT_Item FROM OPENQUERY(PLPPROD_LS, ''#SQL'')',
#param_list NVARCHAR(MAX) = N'#SQL NVARCHAR(MAX)';
EXEC [dbo].[sp_executesql]
#query,
#param_list,
#SQL;
EDIT:
DECLARE #SQL NVARCHAR(MAX) = 'SELECT ''WIP-''||ITEM_CODE AS TEST FROM ITEM'
DECLARE #query NVARCHAR(MAX) = 'SELECT * INTO GT_Item FROM OPENQUERY(PLPPROD_LS, ''' + #SQL + ''')'
SELECT #query
Result:
SELECT * INTO GT_Item FROM OPENQUERY(PLPPROD_LS, 'SELECT 'WIP-'||ITEM_CODE AS TEST FROM ITEM')
Result is incorrect because it has missing '' near WIP
Correct query:
DECLARE #SQL NVARCHAR(MAX) = 'SELECT ''''WIP-''''||ITEM_CODE AS TEST FROM ITEM'
I'm writing a stored procedure and I'm passing the table names as parameters, but I'm having an error in this part:
DECLARE
#TableA nvarchar(255)='TableA',
#DOCID1 nvarchar(MAX),
#DOCID2 int;
EXEC ('
SELECT TOP (1) '+ #DOCID1 +'=DOCID1,'+ #DOCID2 +'=DOCID2
FROM [' + #TABLEA + ']
ORDER BY DOCID2')
After I run this query I get this error:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '='
I have tried and I can't pinpoint the error, at this point I need some help..
I believe you have to concatenate together your SQL statement as a whole, before executing it:
DECLARE
#TableA nvarchar(255)='TableA',
#DOCID1 nvarchar(MAX),
#SqlStmt NVARCHAR(500),
#DOCID2 int;
SET #SqlStmt = N'SELECT TOP (1) ' + #DOCID1 + N' = DOCID1, ' + #DOCID2 + N' = DOCID2 FROM [' + #TABLEA + N'] ORDER BY DOCID2';
EXEC (#SqlStmt)
As far as I recall, you cannot have expressions and computations inside the EXEC command - get the statement prepared before hand, then execute it
Also, I'm not entirely sure what those variables of yours hold - #DocID1 and #DocID2 - do you want to set their value, or do they hold the name of another variable to set??
Update: if you actually wanted to set the values of #DocID1 and #DocID2, then your query was wrong to begin with - then you need something like this:
DECLARE
#TableA nvarchar(255) = 'TableA',
#SqlStmt NVARCHAR(500);
SET #SqlStmt =
N'DECLARE #DocID1 NVARCHAR(MAX), #DocID2 INT; ' +
N'SELECT TOP (1) #DOCID1 = DOCID1, #DOCID2 = DOCID2 FROM [' + #TABLEA + N'] ORDER BY DOCID2';
EXEC (#SqlStmt)
but then, those two variables are scoped inside the dynamically executed SQL and aren't available to the "outside" of your script.
What version of SQL Server? The sytax -
DECLARE
#TableA nvarchar(255)='TableA'
is supported only from SQL Server 2008. For older versions you have to write:
DECLARE
#TableA nvarchar(255)
SET #TableA ='TableA'
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