September 9, 2014 at 2:57 am
The below cursor is giving an error
DECLARE @Table_Name NVARCHAR(MAX) ,
@Field_Name NVARCHAR(MAX) ,
@Document_Type NVARCHAR(MAX)
DECLARE @SOPCursor AS CURSOR;
SET
@SOPCursor = CURSOR FOR
SELECT SOPTYPE, TABLE_NAME, Field_Name FROM dbo.SOP_Tables
OPEN @SOPCursor
FETCH NEXT FROM @SOPCursor INTO @Document_Type, @Table_Name, @Field_Name
WHILE @@FETCH_STATUS = 0
BEGIN
DELETE FROM @Table_Name
FETCH NEXT FROM @SOPCursor INTO @Document_Type, @Table_Name, @Field_Name
END
CLOSE @SOPCursor;
DEALLOCATE @SOPCursor;
It gives an error
Msg 1087, Level 16, State 1, Line 15
Must declare the table variable "@Table_Name".
The @Table_Name variable is declared,
If I replace the delete statement (DELETE FROM @Table_Name ) with (PRINT @table_name) it works and print the table names.
Why does the delete statement give an error ?
Best Regards,
September 9, 2014 at 3:33 am
-- You can't specify a table name as a variable in a statement in TSQL. Your best bet is dynamic SQL: http://www.sommarskog.se/dynamic_sql.html
EXEC('DELETE FROM ' + @Table_Name)
-- or
DECLARE @sql NVARCHAR(MAX) = N'DELETE FROM ' + @Table_Name
EXEC sp_executesql @sql
For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
September 9, 2014 at 7:22 am
And you sure don't need a cursor for this.
_______________________________________________________________
Need help? Help us help you.
Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.
Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/
September 9, 2014 at 8:25 am
I agree with Sean, but I feel that that's not everything that you do on your cursor.
To prevent problems if someone messed up with the data on your table, I would use QUOTENAME function to prevent SQL injection.
EXEC('DELETE FROM ' + QUOTENAME(@Table_Name))
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply