From the course: Hands-On Advanced SQL Server: Strategies and Techniques
Unlock this course with a free trial
Join today to access over 25,500 courses taught by industry experts.
Dynamic SQL - SQL Server Tutorial
From the course: Hands-On Advanced SQL Server: Strategies and Techniques
Dynamic SQL
- [Instructor] Sometimes, SQL needs to be flexible. Let's say you want to run the same kind of query over and over, but change something like the filter, the column, or even the table depending on the situation. Well, you can't do that with just regular SQL because it expects the full query to be written ahead of time. That's where Dynamic SQL comes in. Instead of writing one fixed query, we build the query as a string, then ask SQL Server to run it for us. It's powerful, but we need to use it carefully. Let's start with a regular static query, the one that's in front of us here. This query finds all actors born in a specific country. Now this works just fine, but what if we want to change the nationality filter, using a variable? Normally, we can't dynamically change the column value in a static query, and this is where Dynamic SQL comes in. We're just building a string in this query here. To insert the variable into the SQL text, we use our concatenation string here. Let me just…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.