Click here to Skip to main content
15,885,216 members
Articles / Database Development
Alternative
Tip/Trick

Always use Binding Variables in SQL queries

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
28 Apr 2011CPOL 11.8K   4
Thanks for that. In MS SQL Server, I use the following technique to avoid full compile:DECLARE @sql VARCHAR(100)DECLARE @pk INTSET @pk = 2SET @sql = 'SELECT id, pcname FROM pod WHERE id = ' + CAST(@pk AS VARCHAR)EXEC (@sql)-- or -- EXEC sp_sqlexec @SQL
Thanks for that. In MS SQL Server, I use the following technique to avoid full compile:

SQL
DECLARE @sql VARCHAR(100)
DECLARE @pk INT

SET @pk = 2
SET @sql = 'SELECT id, pcname FROM pod WHERE id = ' + CAST(@pk AS VARCHAR)

EXEC (@sql)

-- or -- 

EXEC sp_sqlexec @SQL

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralOr you could write a stored procedure and not only have a (o... Pin
John B Oliver19-May-11 17:14
John B Oliver19-May-11 17:14 
GeneralReason for my vote of 5 Good example Pin
Wild-Programmer28-Apr-11 23:59
Wild-Programmer28-Apr-11 23:59 
GeneralBetter for using query plan caching must be: <code> SET @sql... Pin
Gluck28-Apr-11 17:11
Gluck28-Apr-11 17:11 
GeneralHow does this avoid recreating the query plan? Pin
AspDotNetDev28-Apr-11 14:21
protectorAspDotNetDev28-Apr-11 14:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.