I wrote a stored procedure that returns nvarchar variable that contains some generated SQL query, and second procedure, that generates XML using FOR XML PATH.
I want to modify my procedure that generates XML and add content of my generated query from first procedure into generated XML.
Part of my procedure that generates XML:
SELECT #SQLStr = 'SELECT';
DECLARE #tmp varchar(100), #tmpkod varchar(max);
DECLARE c CURSOR LOCAL READ_ONLY FOR
SELECT tableName, tableCode FROM #TableNames
OPEN c
FETCH NEXT FROM c INTO #tmp, #tmpkod;
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #i = #i - 1;
SELECT #SQLStr = #SQLStr + '(SELECT TOP 10 * FROM ' + #tmp + ' FOR XML PATH(''row''), TYPE) AS ' + #tmp + ',
'
EXEC GenerujSelectazXML #tmp, #tmpcode output;
SELECT #SQLStr = #SQLStr + '(SELECT ' + #tmpCode + ' FOR XML PATH (''row''), TYPE) AS ' + #tmp + '_TEST'
SELECT #tmpcode
IF (#i <> 0) SELECT #SQLStr = #SQLStr + ',
'
ELSE SELECT #SQLStr = #SQLStr + '
'
FETCH NEXT FROM c INTO #tmp, #tmpkod;
END
CLOSE c; DEALLOCATE c;
SELECT #SQLStr = #SQLStr + 'FOR XML PATH(''''), ROOT(''root'')';
EXEC (#SQLStr)
I cannot simply put content of a query into XML, because it contains some special characters like " < ", " > ", and they are introducing/ending xml tags.
So i thought that putting query command into XML comment will solve my problem.
I tried this:
SELECT #SQLStr = '<!--' + #tmpCode + '-->';
and it didn't help, I got error:
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '<'.
Msg 137, Level 15, State 1, Line 4
Must declare the scalar variable "#xml".
Msg 137, Level 15, State 2, Line 216
Must declare the scalar variable "#xml".
Msg 156, Level 15, State 1, Line 217
Incorrect syntax near t he keyword 'FOR'.
Msg 137, Level 15, State 1, Line 219
Must declare the scalar variable "#xml".
Msg 137, Level 15, State 2, Line 416
Must declare the scalar variable "#xml".
Msg 156, Level 15, State 1, Line 417
Incorrect syntax near the keyword 'FOR'.
Msg 137, Level 15, State 1, Line 419
Must declare the scalar variable "#xml".
Msg 137, Level 15, State 2, Line 540
Must declare the scalar variable "#xml".
I also tried this:
SELECT #SQLStr = '<![CDATA[' + #tmpCode + N']]>';
it didn't help, either.
Error message that I got:
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '<'.
Msg 103, Level 15, State 4, Line 3
The identifier that starts with CDATA[DECLARE #xml xml SELECT TOP 1 #xml = x FROM iksemel ORDER BY id INSERT INTO ARTYKUL_TEST(ID_ARTYKULU,ID_MAGAZYNU' is too long. Maximum length is 128.
Msg 105, Level 15, State 1, Line 541
Unclosed quotation mark after the character string ')'.
Please help
Could you provide an example of the xml you're trying to generate? Based on the code you posted, I'm assuming it looks something like this.
<root>
<Instructors>
<row>
<InstructorName>Graff</InstructorName>
</row>
</Instructors>
<Instructors_TEST>
<row>0</row>
</Instructors_TEST>
</root>
You'll need to modify your generated SQL to be more like this:
SELECT (
SELECT * FROM Instructors FOR XML PATH('row'), TYPE
) AS Instructors,
(
SELECT 0 FROM Instructors FOR XML PATH('row'), TYPE
) AS Instructors_TEST
FOR XML PATH(''), ROOT('root')
The problem is not with the value (query) you're trying to store in the xml. Do a SELECT on the #tmpCode, paste it into the editor, and check whether its a valid string. It's not.
In your code, you'd get this:
SELECT #tmpCode = '''SELECT value(''ID_ARTYKULU[1]'')'''
--'SELECT value('ID_ARTYKULU[1]')'
But you want to use this:
SELECT #tmpCode = '''SELECT value(''''ID_ARTYKULU[1]'''')'''
--'SELECT value(''ID_ARTYKULU[1]'')'
A ghetto fix would be to replace your #tmpCode section with this:
SELECT #tmpCode = N'''' + REPLACE('SELECT value(''ID_ARTYKULU[1]'')', N'''', N'''''') + N''''
Since you're using dynamic SQL, you need to be very careful when escaping quotes.
Related
Normally, we can cast a single record query to nvarchar(max). For example:
DECLARE #result NVARCHAR(MAX) = N'';
SELECT
#result = #result + (CAST((SELECT TOP(3) name AS td
FROM
sys.databases
FOR XML PATH ('')) AS NVARCHAR(MAX)));
SELECT #result
But how can I do the same thing when the query has CTE? The query still returns a single row. For example:
DECLARE #result NVARCHAR(MAX) = N'';
SELECT
#result = #result + (CAST((WITH d AS
(SELECT name FROM sys.databases)
SELECT TOP(3) name AS td
FROM d
FOR XML PATH ('')) AS NVARCHAR(MAX)));
SELECT #result
When I execute it, I got the following errors:
Msg 156, Level 15, State 1, Line 7
Incorrect syntax near the keyword 'WITH'.
Msg 319, Level 15, State 1, Line 7
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
Msg 102, Level 15, State 1, Line 8
Incorrect syntax near ')'
I know I can use a derived table or subquery etc. But in my case, the query is very complex and it has several CTEs in it, which I don't want to touch.
Your CTE definition should not be on select statement:
DECLARE #result NVARCHAR(MAX) = N'';
WITH d AS (SELECT name FROM sys.databases)
SELECT #result = #result + (CAST((SELECT TOP(3) name AS td FROM d FOR XML PATH ('')) AS NVARCHAR(MAX)));
SELECT #result
I'm trying to execute a dynamic SQL query, but I'm getting an error Msg 105, Level 15, State 1, Line 1
Unclosed quotation mark after the character string '2020-09-15 18:'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '2020-09-15 18:'
There must be something wrong with the datetime variable.
Can anybody suggest how this should be done properly ?
declare #paramDailyOutput nvarchar(100), #retrieveDailyVal real
declare #paramDaily float
declare #retrieveDailyID varchar(100) = 'table_53'
declare #startTime datetime, #currTime datetime = GETDATE()
set #startTime = DATEADD(hour, -1, #currTime)
set #paramDailyOutput = 'SELECT #paramDaily = max(value) - min(value) FROM ' + #retrieveDailyID + ' where read_date between ''' + convert(nvarchar(200), #startTime, 120) + ''' and ''' + convert(nvarchar(200), #currTime, 120) + ''''
exec sp_executesql #paramDailyOutput, N' #paramDaily float OUTPUT', #paramDaily = #paramDaily output
select #paramDaily
You strings are too short, you're going way over 100 characters.
Try changing everything to 250 or even 300 characters. Or better yet, NVARCHAR(1000).
When I am executing this dynamic query via this, I am trying to fetch the complete name of customer (First_Name + Last_Name).
Please let me know what I am doing wrong here.
Code is here:
Set #tblName ='Customer_List'
Exec (N'Select First_Name'+' '+'Last_Name from'''+ #tblName+'''
where Customer_Id in ('+ 'cast(1000 as nvarchar(10))' );
I am getting this error:
(1 row(s) affected)
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'dbo.Customer_List'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'dbo.Customer_List'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'dbo.Customer_List'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'dbo.Customer_List'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'dbo.Customer_List'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'dbo.Customer_List'.
Try this
Set #tblName ='Customer_List' Exec (N'Select First_Name'+' '+'Last_Name from '+ #tblName+' where Customer_Id in ( cast(1000 as nvarchar(10) ))' );
Try this .
1) Add space after FROM.
2) Add the ) bracket in (10)))
3) Remove the '' arround the table name.
DECLARE #tblName AS VARCHAR(100)
Set #tblName ='TempTable'
Exec (N'Select First_Name'+' '+'Last_Name from '+ #tblName+'
where Customer_Id in ('+ 'cast(1000 as nvarchar(10)))' );
try following query:
DECLARE #sql as VARCHAR(1000)
SET #sql = 'Select First_Name + '' ''+ Last_Name from '+ #tblName + ' where Customer_Id in (' + CAST(1000 AS VARCHAR(1000)) + ')'
Exec (#sql)
I wrote the following code:
Declare #DaataBaseName2 varchar(50)
set #DaataBaseName2 = 'LUNDB14644A01' -- #DaataBaseName
USE #DaataBaseName2 --LUNDB14644A01
GO
I received following error:
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '#DaataBaseName2'.
Why?
You will have to execute your code via dynamic SQL. You have to be careful with dynamic sql as it can lead to sql injection attack.
Here is a small scale sample of how to use a dynamic database.
Declare #DaataBaseName2 varchar(50),
#sql nvarchar(Max)
set #DaataBaseName2 = 'master' -- #DaataBaseName
set #sql = 'USE ' + #DaataBaseName2 + ';' + CHAR(13)
SET #sql = #sql + 'SELECT db_name()'
exec sp_executesql #sql
GO
I would like to read rows from txt files and make some processing in the procedure TESTSP. But I do have some error. How should I rewrite my queries? Best regards.
Code:
DECLARE #i int
set #i =0
WHILE(#i<85)
begin
#i=#i+1;
if(#i<10)
begin
exec TESTSP'C:\dosya\X_20130208_0'+#i+'.txt'
end
else
begin
exec TESTSP 'C:\dosya\X_20130208_'+convert(#i as varchar(2))+'.txt'
end
end
Errors:
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near '#i'.
Msg 102, Level 15, State 1, Line 8
Incorrect syntax near '+'.
Msg 102, Level 15, State 1, Line 12
Incorrect syntax near '+'.
You need to convert or cast #i (int) to varchar for string concatenation. Also note the syntax of Convert as you have used cast syntax to convert.
declare #i int = 0, #path varchar(500)
while(#i<85)
begin
--You can simplify (or remove if condition) using right() function as below
--Assign #path here before calling stored procedure
select #i = #i + 1,
#path = 'C:\dosya\X_20130208_' + right(100 + #i, 2) + '.txt'
--Execute stored procedure here
exec TESTSP #path
end