Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 execute dynamic sql

Author  Topic 

arkiboys
Master Smack Fu Yak Hacker

1433 Posts

Posted - 2012-01-31 : 10:03:46
Hi,
A few questions please:

1- When executing a dynamic sql, why is it better to use nvarchar than varchar ?
declare @sql nvarchar(max) = 'select field1 from tblMain'

2-
Why is it better to use the following
sp_executesql @sql
rather than execute (sql) ?

Thanks

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-01-31 : 10:14:20
With sp_executesql, it is a requirement that you use unicode strings, not a choice.

As for why sp_executesql is preferable, among other things, a) less susceptible to sql injection, b) possibility of reusing execution plans etc.

Sommarskog's blog here is a good read: http://www.sommarskog.se/dynamic_sql.html
Go to Top of Page

arkiboys
Master Smack Fu Yak Hacker

1433 Posts

Posted - 2012-01-31 : 10:17:14
Thanks
Go to Top of Page
   

- Advertisement -