Wednesday, February 15, 2012

Dynamic SQL in cursor

I need to pass a list of values into a cursor as such...

DECLARE
@.group_SQL varchar(255)

SET @.group_SQL = 'SELECT group_id FROM groups where group_id in (' + @.group_id + ')'

DECLARE groupContact_import_cursor CURSOR
FOR EXEC(@.group_SQL)
OPEN groupContact_import_cursor
FETCH NEXT FROM groupContact_import_cursor INTO @.group_id
WHILE (@.@.FETCH_STATUS = 0)
BEGIN
insert into groupContacts (group_id, contact_id) values (@.group_id, @.new_cid)
FETCH NEXT FROM groupContact_import_cursor INTO @.group_id
END
CLOSE groupContact_import_cursor
DEALLOCATE groupContact_import_cursor

But MS SQL doesn't seem to like the FOR EXEC(@.group_SQL). Can someone shed some light?

TIAI think it should work like this.

DECLARE groupContact_import_cursor CURSOR
FOR SELECT group_id FROM groups where group_id = @.group_id|||Why? A contact can be assigned to many group_id values, not just one.|||SET @.group_SQL = 'SELECT group_id FROM groups where group_id in (' + @.group_id + ')'

set @.group_SQL = 'DECLARE groupContact_import_cursor CURSOR FOR ' + @.group_SQL

exec (@.group_SQL)
OPEN groupContact_import_cursor
...|||bingo, that did it. I didn't know I needed to include the DECLARE portion, oh well...

Thanks a lot.|||bingo, that did it. I didn't know I needed to include the DECLARE portion, oh well...

Thanks a lot.

It did?

I'm highly sceptical...

What does @.group_id look like

No comments:

Post a Comment