Learn more about SQL Server tools

mssqltips logo
 

Tutorials          DBA          Dev          BI          Career          Categories          Webcasts          Whitepapers          Today's Tip          Join

Tutorials      DBA      Dev      BI      Categories      Webcasts

DBA    Dev    BI    Categories

 
Simplify SQL Server Database Development     ====>    Webcast Registration
 

SQL Server Video Creating Dynamic SQL Commands


By:   |   Read Comments (2)   |   Related Tips: More > Dynamic SQL



 






Enter your business email address to
get free SQL Server tips.

Problem / Solution

Having the ability to write dynamic SQL statements is sometimes the only option besides having to write several versions of a SQL statement to cover all possible scenarios. In this video tip we look at a few different simple examples of how you can create SQL statements that are dynamic in nature.  Note that dynamic SQL statements should be your last option, but in some cases this may be the only option.

Key Learning Items

  • Building dynamic T-SQL statements
  • Using SQL Server variables
  • Using EXEC to execute dynamic SQL
  • Using sp_executesql to execute dynamic SQL

Read Companion Tip
Click Here

Last Update:


next webcast button


next tip button



About the author
MSSQLTips author Greg Robidoux Greg Robidoux is the President of Edgewood Solutions and a co-founder of MSSQLTips.com.

View all my tips





Post a comment or let the author know this tip helped.

All comments are reviewed, so stay on subject or we may delete your comment. Note: your email address is not published. Required fields are marked with an asterisk (*).

*Name    *Email    Email me updates 


Signup for our newsletter
 I agree by submitting my data to receive communications, account updates and/or special offers about SQL Server from MSSQLTips and/or its Sponsors. I have read the privacy statement and understand I may unsubscribe at any time.



    



Tuesday, September 30, 2014 - 9:41:48 AM - Greg Robidoux Back To Top

Hi Ken,

In example 3 the parameter @city just needs to hold the value, we don't need to pass the single quotes into the command.  This parameter value is then passed in the sp_executesql command.  Since we don't need to have the value quoted as we did in example 2, we just need to set the parameter value without additional single quotes.

-Greg


Tuesday, September 30, 2014 - 7:27:22 AM - Ken Uber Back To Top

You didn't explain why the @city variable did not require the triple quote for sp_executesql as required for exec.

 

 

 

 

 

 


Learn more about SQL Server tools