Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run generated SQL from a variable?

I've tried running my SQL (in T-SQL) (I just genereated into a variable) but I can't get it to run. What I want to do is: 1. Run big SQL from Program 2. Big SQL generates selct-SQL 3. run generated sql like normal select and receive data like normal. I thought it could be done done with sp_executesql but it looks like it's not right in my case.

What I'm trying looks like this:

declare @sql varchar(max)

set @sql = 'select x, y from z'

exec @sql --this is the point where im stuck.

I know this must be quite a basic question, but I couldn't find something that fits to my problem on google.

Thanks for your help!

Update I solved my problem by using sp_sqlexec (which isn't supported anymore but works like I wanted).

declare @sql varchar(max)

set @sql = 'select x, y from z'

exec sp_sqlexec @sql 

The correct solution is sp_executesql! (see sp_sqlexec vs. sp_executesql) For my problem it would be quite time consuming if i would "rebuild" everything that I could use it.

Thanks for your help guys!

like image 507
RL4P Avatar asked Oct 24 '11 08:10

RL4P


People also ask

How do I run a dynamic SQL query?

To run a dynamic SQL statement, run the stored procedure sp_executesql as shown below : EXEC sp_executesql N'SELECT statement'; Use prefix N with the sp_executesql to use dynamic SQL as a Unicode string.

How do I use a variable in SQL Select statement?

The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.

Can we execute dynamic SQL in function?

You can't execute dynamic sql in user defined functions. Only functions and some extended stored procedures can be executed from within a function.


2 Answers

You need parentheses exec (@sql)

SQL Server will look for a stored procedure of the name in the @sql variable without this and complain Could not find stored procedure 'select x, y from z'.

If you are using dynamic SQL See The Curse and Blessings of Dynamic SQL for a good article on the topic.

like image 154
Martin Smith Avatar answered Jan 15 '23 19:01

Martin Smith


You can also use sp_executesql, but note that it needs NVARCHAR (Unicode)

Also, if you are building dynamic filters, you can pass in parameters as per below

declare @SQL nvarchar(max)
set @SQL = N'select x, y from z where x = @someFilter'
exec sp_executesql @SQL, N'@someFilter bigint', @someFilter = 6034280
like image 22
StuartLC Avatar answered Jan 15 '23 18:01

StuartLC