DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Data Engineering
  3. Databases
  4. Introduction to Dynamic SQL

Introduction to Dynamic SQL

Dynamic SQL affords the opportunity to execute SQL that will then go ahead and generate and execute another SQL statement. Read on to learn the basics of it.

Mateusz Komendołowicz user avatar by
Mateusz Komendołowicz
·
Jul. 12, 17 · Tutorial
Like (10)
Save
Tweet
Share
39.76K Views

Join the DZone community and get the full member experience.

Join For Free

The idea of using dynamic SQL is to execute SQL that will potentially generate and execute another SQL statement. While querying data, you might want to dynamically set columns you would like to query. On the other hand, you might want to parametrize tables on which you want to operate.

The first idea one might come up with is to use variables and set them as required column names or table names. However, such an approach is not supported by T-SQL.

DECLARE @tablename AS NVARCHAR(255) = N'dbo.Table';
SELECT *
FROM @tablename
-- this code will fail

T-SQL does not permit replacing many parts of code with variables. For example:

  • Table name (FROM clause).
  • Database name (USE clause).
  • Column names (SELECT, WHERE, GROUP BY, HAVING, and ORDER BY clauses).
  • Lists (IN, PIVOT clauses).

Dynamic SQL Examples

The solution is to use dynamic SQL. But what it is in practice? In short, it is all about executing queries as strings.

An example of putting the query to the string:

DECLARE @query AS NVARCHAR(255) = N'SELECT * FROM dbo.Table';
SELECT @query AS query;

An example of executing the query, which is in the string (dynamic SQL):

DECLARE @query AS NVARCHAR(255) = N'SELECT * FROM dbo.Table';
EXEC(@query);

So as we can see, the EXEC statement is used to dynamically execute the query that is stored in the nvarchar variable. Let’s go back to the example with dynamically choosing which columns from which table we would like to query. The solution for this might look like this procedure:

IF OBJECT_ID('dbo.queryData', 'P') IS NOT NULL
	DROP PROC dbo.queryData;
GO

CREATE PROC dbo.queryData
	@tablename AS NVARCHAR(255)
	,@columnnames AS NVARCHAR(255)
AS
BEGIN
	DECLARE @SQLString AS NVARCHAR(MAX);
	SET @SQLString = N'SELECT ' +@columnnames+N' FROM ' + @tablename; 
	EXEC(@SQLString);
END

...which you can execute like every other T-SQL procedure:

EXEC dbo.queryData 'dbo.Table', 'id, firstname, lastname, age'

As the last example, let’s create a procedure that will allow the user to query all data from the selected table with the selected predicate in the WHERE  clause.

USE TSQL2012;
GO
IF OBJECT_ID('dbo.queryData', 'P') IS NOT NULL
	DROP PROC dbo.queryData;
GO

CREATE PROC dbo.queryData
	@tablename AS NVARCHAR(255)
	,@column AS NVARCHAR(255)
	,@predicateOperator AS NVARCHAR(255)
	,@predicateValue AS NVARCHAR(255)
AS
BEGIN
	DECLARE @SQLString AS NVARCHAR(MAX);
	SET @SQLString = N'SELECT * FROM ' + @tablename + N' WHERE ' + @column + @predicateOperator+@predicateValue ; 
	EXEC(@SQLString);
END

EXEC dbo.queryData 'dbo.Table', 'age','>=','18'

Dynamic SQL Gives You More Possibilities

In T-SQL, you might also execute dynamic SQL with the sp_executesql stored procedure, which is an alternative to EXEC. It allows you to use parameters: both input and output. It is generally better than EXEC when it comes to performance because SQL Server might reuse cached execution plans.

sql Database

Published at DZone with permission of Mateusz Komendołowicz, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Assessment of Scalability Constraints (and Solutions)
  • Introduction To OpenSSH
  • How We Solved an OOM Issue in TiDB with GOMEMLIMIT
  • Implementing PEG in Java

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: