I need to use exec to create a temp table because of parameterized information in the statement. The data in @id_data comes from a remote location and I don't know what it will be on any particular run.
I hope someone can explain what is wrong with this code. I've simplified it, mostly to avoid printing out my client's code, but this is giving the same error. It seems to think I'm trying to call a procedure, rather than execute a "SELECT INTO" statement. If I run the string by itself without using exec, it completes with no error. I know there's extra concatenations but that isn't making any difference. I've also tried having the assignment on a single line.
Here's the code that produces this problem:
create procedure p_foo
as
BEGIN
DECLARE
@id_data varchar(20),
@exec_string varchar(500)
select @id_data = '1, 2, 3, 4'
CREATE table tempdb..xref (gsid int, sys_id int, status varchar(9), book int)
CREATE table tempdb..rollup (code varchar(20), descr varchar(20), gsid int)
SELECT @exec_string = 'SELECT DISTINCT a.book, isnull(RIGHT(b.code,4),'''') as code, isnull(b.descr,'''') as descr ' +
'INTO #info FROM tempdb..xref a, tempdb..rollup b WHERE a.gsid = b.gsid AND a.sys_id in ( ' + @id_data +
' ) AND upper(a.status) = ''ACTIVE'''
print @exec_string
exec @exec_string
END
The output with the error is:
SELECT DISTINCT a.book, isnull(RIGHT(b.code,4),'') as code, isnull(b.descr,'')
as descr INTO #info FROM tempdb..xref a, tempdb..rollup b WHERE a.gsid = b.gsid
AND a.sys_id in ( 1, 2, 3, 4 ) AND upper(a.status) = 'ACTIVE'
Msg 2812, Level 16, State 5:
Server 'DNYDS47500', Procedure 'p_foo', Line 20:
Stored procedure 'SELECT DISTINCT a.book, isnull(RIGHT(b.code,4),'') as code,
isnull(b.descr,'') as descr INTO #info FROM tempdb..xref a, tempdb..rollup b
WHERE a.gsid = b.gsid AND a.sys_id in ( 1, 2, 3, 4 ) AND upper(a.status) =
'ACTIVE'' not found. Specify owner.objectname or use sp_help to check whether
the object exists (sp_help may produce lots of output).
(return status = 0)