Execute Dynamic SQL Commands in SQL Server

August 9, 2022 | Author: Anonymous | Category: N/A
Share Embed Donate


Short Description

Download Execute Dynamic SQL Commands in SQL Server...

Description

 

Execute Dynamic SQL commands in SQL Ser ver

http://w w w.mssqltips.com/tip.asp?tip=1160

 join the community community

Ho om me

T iip ps

To oo o lls s

Tu utt or or iia a ls ls

W eb eb c ca a st st s

W hi hi te te pa pa p e err s

Q ue ue st st io io n ns s

Subscribe:

Learn more about SQL Server

Execute Dynamic SQL commands in SQL Server By: Greg Robidoux | Robidoux | Comments (3) | (3) | Print | Print |

 

Share

 

1

More SQL Server Tools

Expand your SQL Server horizons with a Kindle loaded with 5 eBooks

SQL Sentry Performance Advisor® for SQL Server

< Prev - | 1 | 2 | 3 | 4 | - Next >

SQL Refactor SQL comparison toolset

Problem In some applications applications having hard coded SQL statements is not appealing, because of the dynamic nature of the queries being issued against the database server. Because of this sometimes there is a need to dynamicall dynamically y create a SQL statement on the fly and then run tha t command. command. This can be done quite sim simply ply from the application perspective perspective where the statement is built on the fly whether you are using ASP.NET, ColdFusion or any oth er programming language. But how do you do this from within a SQL Server stored procedure?

SQL diagnostic manager SQL Virtual Restore

Solution SQL Server offer s a few ways of running a dynamically dynamically built SQL statement. These ways are: 1. Writing a query with parameters 2. Using EXEC 3. Using sp_executesql 1. Writing a query with parameters This first approach is pretty straight forward if you only need to pass parameters into your WHERE clause of your SQL statement. Let's say we need to find all records from the customers customers table where City = 'London'. This can be done easily such as th e following example shows. DECLARE @city varchar(75) SET @city = 'London' SELECT * FROM customers WHERE City = @city

SQL Server Tips Latest Active Comments Related

Latest 2. Using EXEC With this approach you are building the SQL statement on the fly and can pretty much do whatever you need to in order to construct the statement. Let's say we want want to be able to pass in the column list along with with the city. For this ex ample we want to get columns Custom CustomerID, erID, ContactName and City where City = 'London'. As you can see from th is example handling the @city value is not at straight forward, because you also need to define the extra quotes in order to pass a character character value into the query. These extra quotes could al also so be done within within the statement, but either way you need to specify the extra single quotes in order for the query to be built correctly and therefore run. DECLARE @sqlCommand varchar(1000) DECLARE @columnList varchar(75) DECLARE @city varchar(75) SET @columnList = 'CustomerID, ContactName, City' SET @city = '''London''' SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = ' + @city EXEC (@sqlCommand)

SQL Server script to rebuild all indexes for all tables and all databases Locking Down PII Data Data in SQL S erver - Part 2 Restoring a SQL Server database that uses Change Data Capture Identifying PII Data to Lock Down in SQL Server - Part 1 Remove HTML tags from strings using the SQL Server CLR Getting started with Code Snippets feature of SQL Server Denali SQL Server Stored Procedure Tutorial SQL Server Central Management Server Security Moving database files for a r eplicated SQL Server database

3. sp_exectesql With this approach you have the ability to still dynamically build the query, but you are also able to still use parameters as you could in example 1. This saves saves the need to have to deal with the extra quotes to get the query to build correctly. In addition, with using this ap approach proach you can ensure that the data values being passed into the query are the correct datatypes. DECLARE @sqlCommand nvarchar(1000) DECLARE @columnList varchar(75) DECLARE @city varchar(75) SET @columnList = 'CustomerID, ContactName, City' SET @city = 'London' SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = @city' EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city

Maintain SQL Server Replication using Source Control

Active Comments Index Fragmentation Report in SQL Server 2005 and 2008 (4) Restoring a SQL Server database that uses Change Data Capture (2) Locking Down PII Data Data in SQL S erver - Part 2 (1) Performance Advantages of SQL Server Filtered Statistics (2) Collecting SQL Server performance counter data for trending (2) SQL Server script to rebuild all indexes for all tables and all databases (17)

1 de 3 Execute Dynamic SQL commands in SQL Ser ver

28/06/2011 10:02 p.m. http://w w w.mssqltips.com/tip.asp?tip=1160

 

Getting started with Code Snippets feature of SQL Server Denali (0) SQL Server 2005 Database Mail Install Hangs (1) Introduction to Utility Control Points in SQL Server 2008 R2 (1) So here are three different ways of writing dynamic queries. In addition to the above, here are som some e other articles that give you other perspectives on setting up and using dynamic SQL. The Curse and Blessings of Dynamic SQL Introduction to Dynamic SQL (Part 1) Introduction to Dynamic SQL (Part 2)

SQL Server snapshot replication fails when trying to import data from the distributor (2)

Related Dynamic SQL execution on remote SQL Server using EXEC AT

Next Steps If at all possible look at avoiding the use of dynamic SQL especially where you start to manipulate the over all query string. This could p potentially otentially open up other areas of concern such as SQL Injection and Injection and performance issues. Look into using dynamic SQL in your stor ed procedures by employing one of the thr ee techniques above instead having the code generated from your front end application.

Last Update: 1/19/2007 < Prev - | 1 | 2 | 3 | 4 | - Next >

Run a Dynamic Query against SQL Server without Dynamic SQL Recover from a SQL Injection Attack on SQL Server Using the CASE expression instead of  dynamic SQL in SQL Server Execute Dynamic SQL commands in SQL Server

  Sponsor Information Try the free performance monitoring tool from Idera! SQL Backup Pro was the smartest kid at school. Head of the class for compression, encryption and centralized management. Discover why. SQL Server Issues? Not sure where to turn for answers? Innovative SQL DBA consultants Make the most of MSS QLTips.. QLTips...Sign-up .Sign-up for the n ewsletter Valuable SQL Server web casts on Performance Tuning, Development, Development, Administration, Disaster Recovery, Replication and more...

Community Questions Latest Active Questions

Latest extended property SQL 2005 replication in sql server replication in sql server SQL Server process stuck in killed\rollback killed\rollback state (SQL SERVER 2008) Develop the Report or query for listing the database name which does not have database extendend property SSRS 2008 Data Driven Subscriptions to SSAS cube for retrieving Roles membership data Tables names are not being diskpalyed in Index Fragmentation list SQL express 2005 installed on Windows 7 OS having live IP not getting connected to

2 de 3 Execute Dynamic SQL commands in SQL Ser ver

28/06/2011 10:02 p.m. http://w w w.mssqltips.com/tip.asp?tip=1160

 

desktop application when tried connect why we do monitoring in sql server and what is the benefit of monitoring in sql server

Active Questions replication in sql server (1) SQL Server process stuck in killed\rollback killed\rollback state (SQL SERVER 2008) (1) SSRS 2008 Data Driven Subscriptions to SSAS cube for retrieving Roles membership data (1) SQL express 2005 installed on Windows 7 OS having live IP not getting connected to desktop application when tried connect (1) Tables names are not being diskpalyed in Index Fragmentation list (1) SQL 2008 Cube Structure Diagram just like in SQL 2000 (1) Filtering, Sorting, Drilling in SSRS 2005 Reports (1) SQL cluster installation (3) Report Builder 3.0 charts (1) Deploy Sql Server A nalysis Services Cube in FrontEnd (1)

Announcements Events Giveaways Contribute

Events Free Live Webcast TempDB: Performance and Man ageability (July 13th)

Giveaways Giveaways Win a Kindle with SQL Server eBooks MSSQLTips is giving away a Kindle with SQL Server eBooks. The winner will be selected on July 20, 2011.

Contribute Contribute and make some money! Become a MSSQLTips author Share your knowledge about SQL server with the MSS QLTips com community. munity. Just about every day you probably learn something new, so share that knowledge. Copyright (c) 2006-2011 Edgewood Solutions, LLC All LLC All rights reserved privacy privacy |  | disclaimer disclaimer |  | copyright | copyright | advertise advertise |  | contribute contribute |  | feedback feedback |  | giveaways | giveaways | user groups | groups | about Some names and products listed are the registered tr trademarks ademarks of their respective owners.

CareerQandA.com | CareerQandA.com | MSSharePointTips.com | MSSharePointTips.com | MSSQLTips.com

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF