开发者

Stored procedure SQL SELECT statement issue

I am using SQL Server 2008 Enterprise on Windows Server 2008 Enterprise. In a stored procedure, we ca开发者_运维技巧n execute a SELECT statement directly. And it could also be executed in this new way, I am wondering which method is better, and why?

New method,

declare @teststatement varchar(500)

set @teststatement = 'SELECT * from sometable'

print @teststatement

exec (@teststatement)

Traditional method,

SELECT * from sometable

regards, George


FYI: it’s not a new method, it is known as Dynamic SQL.

Dynamic SQL are preferred when we need to set or concatenate certain values into sql statements.

Traditional or normal way sql statements are recommended, because stored procedures are complied. Complied on first run "Stored Procedure are Compiled on First Run" , execution plan of statements are being created at the time of compilation.

Dynamic sqls are ignored while creating execution plans, because it is taken as string (VARCHAR or NVARCHAR as declared).

Refer following articles for more details about dynamic query and stored procs
Introduction to Dynamic SQL Part 1
Introduction to Dynamic SQL Part 2
Everything you wanted to know about Stored Procedures


The traditional method is safer, because the query is parsed when you save it. The query in the 'exec' method is not parsed and can contain errors.


The "new" way, as mentioned, has nothing to do with SQL 2008. EXEC has been available for quite some time. It's also - in most cases - a Very Bad Idea.

You lose parameterization - meaning you are now vulnerable to SQL Injection. It's ugly and error-prone. It's less efficient. And it creates a new execution scope - meaning it can't share variables, temp tables, etc. - from it's calling stored proc.

sp_executesql is another (and preferred) method of executing dynamic SQL. It's what your client apps use, and it supports parameters - which fixes the most glaring problem of EXEC. However, it too has very limited use cases within a stored proc. About the only redeeming use is when you need a dynamic table or column name. T-SQL does not support a variable for that - so you need to use sp_executesql. The number of times you need or should be doing that are very low.

Bottom line - you'd be best off forgetting you ever heard of it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜