Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using EXEC() or SP_EXECUTESQL with SQL Common Table Expressions

How do I use EXEC(@SQL) or EXEC SP_EXECUTESQL(@SQL) with Common Table Expressions?

Below does not work.

WITH CTE_Customer (ID,  Name)
AS
(
    EXEC (@strSqlCommand)
)
like image 616
Deepfreezed Avatar asked Jul 20 '11 17:07

Deepfreezed


People also ask

What is difference between EXEC and Sp_executesql?

The main difference between the EXEC or EXECUTE operators and the sp_executesql built-in stored procedure is that the EXEC operator is used to execute a stored procedure or a SQL command passed as a string or stored within a variable.

What is EXEC Sp_executesql in SQL?

The sp_executesql is a built-in stored procedure in SQL Server that enables to execute of the dynamically constructed SQL statements or batches. Executing the dynamically constructed SQL batches is a technique used to overcome different issues in SQL programming sometimes.

What are the benefits of using Sp_executesql over EXEC?

sp_executesql allows for statements to be parameterized, Therefore It's more secure than EXEC in terms of SQL injection.

Can we use EXEC in SQL function?

The EXEC command is used to execute a stored procedure, or a SQL string passed to it. You can also use full command EXECUTE which is the same as EXEC.


1 Answers

The short answer is that you cant:

http://msdn.microsoft.com/en-us/library/ms175972.aspx says: "The CTE_query_definition must meet the same requirements as for creating a view" Which basically says that you're restricted to SELECT statements only.

Some workarounds might include using temp tables or table variables, but it really depends on context.

like image 144
Michael J Swart Avatar answered Nov 15 '22 08:11

Michael J Swart