How to use while loop with string joinnig with plus? - sql-server

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

Related

Problem passing a datetime variable into a dynamic SQL query

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).

MS SQL - Where are the syntax and scalar errors?

I've been beating my head over this brick wall all morning. This is a very simplified example of the error(s) I've been receiving. I am using SSMS.
DECLARE #myid nvarchar(10) = '5'
DECLARE #sql nvarchar(2048) = 'SELECT id FROM Applications A WHERE A.id=#myid'
EXECUTE sp_executesql #sql, #myid=#myid
Errors:
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '5'. Msg 137,
Level 15, State 2, Line 1 Must declare the scalar variable "#myid".
Why am I getting the syntax, and scalar errors? #myid is defined, right?
sp_executesql needs to receive a definition of the parameters, which you are missing. So, in your case, you should use:
DECLARE #myid nvarchar(10) = '5';
DECLARE #sql nvarchar(2048) = 'SELECT id FROM Applications A WHERE A.id=#myid';
EXECUTE sp_executesql #sql, N'#myid nvarchar(10)', #myid=#myid;

Syntax error escaping string in SQL Server stored procedure

I am new to SQL Server 2012 and have read in lots of places that we only need to escape the single-quote character, by doubling it up. In most cases this seems to work for me, but I am having particular trouble with the following simple stored procedure:
DECLARE #SQLStr nvarchar(max)
DECLARE #SQLParam nvarchar(max)
DECLARE #SQLParamValues nvarchar(max)
SET #SQLStr = 'UPDATE test_data SET name=#1,name_reservation_date=#2 WHERE id=#3'
SET #SQLParam = '#1 nvarchar(50),#2 datetime2(0),#3 bigint'
SET #SQLParamValues = '#1=N''b''1'',#2=''2014-4-25 12:09:39'',#3=12345'
EXEC( 'EXECUTE sp_executesql N''' + #SQLStr + ''', N''' + #SQLParam + ''', ' + #SQLParamValues)
The error that I am getting is this:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '1'.
Msg 105, Level 15, State 1, Line 1
Unclosed quotation mark after the character string ',#3=12345'.
And the problem is that I am trying to write the value b'1, which I have escaped as b''1. If I write just b1 then there is no problem.
The syntax error is on the last line - i.e. when trying to use the #SQLParamValues string as an argument to my EXEC call.
But I can't see any unclosed quotation mark, can someone help me out? Is there a better approach that I should be taking, to avoid all of these doubling-up of quotes? I've inherited this system from someone else so I'm not entirely convinced at this stage.
You don't need to wrap sp_executesql in another EXEC. Use the syntax below. Note that the parameters' values are passed without a variable:
DECLARE #SQLStr nvarchar(max)
DECLARE #SQLParam nvarchar(max)
SET #SQLStr = N'UPDATE test_data SET name=#1,name_reservation_date=#2 WHERE id=#3'
SET #SQLParam = N'#1 nvarchar(50),#2 datetime2(0),#3 bigint'
EXECUTE sp_executesql #SQLStr, #SQLParam,
#1=N'b''1',#2='2014-4-25 12:09:39',#3=12345

Inserting content of SQL query in XML using FOR XML PATH

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.

Msg 102, Level 15, State 1, Line 3 Incorrect syntax near ' '

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

Resources