3

I'm struggling with a dynamic query in tSQL to be used with Excel ODBC.

SQL Server 2016 via ODBC Driver 11 for SQL Server

I found this article but it only uses the table name stored in a parameter, I'd need the actual table to be within parameter: Simple dynamic TSQL query syntax

declare @t table(value1 int, value2 nvarchar(1024))
insert @t SELECT 1 as value1, 'test' as value2
declare @where nvarchar(max)
declare @query nvarchar(max)
declare @sql nvarchar(max)
set @where = ' WHERE value1 = 1'
set @query = 'Select * from @t'
set @sql = @query + @where
EXEC(@sql)

This results in the error message Must declare the table variable "@t"

Unfortunately I can't use temporary tables as the connector doesn't support temp tables.

My original query is far more complex and contains 6 different parameters all being injected at different points into the query and 2 table-parameters that hold temp results

Thanks in advance

1
  • Why does it have to be a table? It looks like you want to use some variables and be able to use them in JOIN clause. Commented Feb 9, 2018 at 15:10

1 Answer 1

1

You just need to declare your table as part of your query. The table is declared and recognized in that scope:

declare @t table(value1 int, value2 nvarchar(1024))
insert @t select 1 as value1, 'test' as value2
declare @where nvarchar(max)
declare @query nvarchar(max)
declare @sql nvarchar(max)
set @where = ' where value1 = 1'
set @query = 'declare @t table(value1 int, value2 nvarchar(1024)) 
              insert @t select 1 as value1, ''test'' as value2 
              select * from @t'
set @sql = @query + @where
exec(@sql)

Result:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.