I want to create a SP that have 2 String parameters for 2 table names. In the SP I use dynamic SQL to modify one of the tables, but the other is inside a cursor, and I cant use dynamic SQL after the "FOR"
ALTER PROCEDURE NameProcedure @SourceTable VARCHAR(100),@DestinationTable VARCHAR(100)
AS
BEGIN
DECLARE @AddressSource VARCHAR(100), @AddressDestination VARCHAR(100)
SELECT @AddressSource = '[Test_Toa].[dbo].[' + @SourceTable + ']'
SELECT @AddressDestination = '[Test_Toa].[dbo].[' + @DestinationTable + ']'
--Source Table columns
DECLARE @id int, @idmercado int, @idcadena int, @barcode nvarchar(255),@Complete_P nvarchar(MAX)
DECLARE @Cursor CURSOR
SET @Cursor = CURSOR FOR
--HEREE ITS MY PROBLEM :(!!!!!
SELECT id, idmercado, idcadena, barcode, precios + ',' FROM @AddressSource
OPEN @Cursor
FETCH NEXT
FROM @Cursor INTO @id,@idmercado,@idcadena,@barcode,@Complete_P
WHILE @@FETCH_STATUS = 0
BEGIN
--bla bla code
FETCH NEXT
FROM @Cursor INTO @id,@idmercado,@idcadena,@barcode,@Complete_P
END
CLOSE @Cursor
DEALLOCATE @Cursor
END
I just want to declare a cursor for the table that the user gives
Well, you need to write a dynamic sql statement. Just as an hint. You can copy the values from your given source table into a temp table, generate a cursor on the temp table, iterate through it and deallocate the cursor afterwards and drop the temp table. :-)
Here a short demo code:
Beware, I just have written this in notepad without any database. But I'm quite sure it does it's job.
This just works if all available variants of @sourceTable have the same column specification. If not, you need to extract the needed columns from information schema and build a more dynamic code.