Home » excel » sql server – Dynamic SQL Query is not returning data into SQL sheet

sql server – Dynamic SQL Query is not returning data into SQL sheet

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have Dynamic SQL Query like below

Dynamic SQL Query:

Declare @Currentmonth4date varchar(8)= convert(varchar(8), DATEADD(month, DATEDIFF(month, 0, GETDATE()), 3),112)
Declare @SQL varchar(max)= 'dbo.Exclusion_Process_Tab1_' + '20181204'

Declare @Select varchar(400) = 'Select * from ' + @SQL

exec (@Select)

I have tried to execute this code from excel’2010 through microsoft query source.

after clicking on return data to option form query window,it is not returning the data into excel sheet.

Please help

How to&Answers:

Did you try to test your dynamic sql

It is returning Select * from dbo.Exclusion_Process_Tab1_20181204

try this

Declare @Currentmonth4date varchar(8)= convert(varchar(8), DATEADD(month, DATEDIFF(month, 0, GETDATE()), 3),112)
Declare @SQL varchar(max)= 'dbo.Exclusion_Process_Tab1_'+ @Currentmonth4date

Declare @Select varchar(400) = 'Select * from '[email protected]

PRINT(@SELECT)

--exec (@Select)

This one is returning

Select * from dbo.Exclusion_Process_Tab1_20190104

After testing comment print and uncomment exec

Before executing your dynamic queries test them with print and see what do they return.

Answer:

You don’t need dynamic SQL, what’s the point?

You just doing something like:

EXEC('SELECT * FROM dbo.Exclusion_Process_Tab1_20181204')

Why not just:

SELECT * FROM dbo.Exclusion_Process_Tab1_20181204

And omit all unnecessary variables.

<a href="https://exceptionshub.com/category/sql-server”>More Answers>