{"id":1741,"date":"2019-04-15T20:23:40","date_gmt":"2019-04-15T13:23:40","guid":{"rendered":"http:\/\/www.sqlservertutorial.net\/?page_id=1741"},"modified":"2020-04-11T20:12:27","modified_gmt":"2020-04-11T13:12:27","slug":"sql-server-dynamic-sql","status":"publish","type":"page","link":"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-dynamic-sql\/","title":{"rendered":"SQL Server Dynamic SQL"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you will learn how to use the SQL Server dynamic SQL to construct general purpose and flexible SQL statements.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='introduction-to-dynamic-sql'>Introduction to Dynamic SQL <a href=\"#introduction-to-dynamic-sql\" class=\"anchor\" id=\"introduction-to-dynamic-sql\" title=\"Anchor for Introduction to Dynamic SQL\">#<\/a><\/h2>\n\n\n\n<p>Dynamic SQL is a programming technique that allows you to construct SQL statements dynamically at runtime. It allows you to create more general purpose and flexible SQL statement because the full text of the SQL statements may be unknown at compilation. For example, you can use the dynamic SQL to <a href=\"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/\">create a stored procedure<\/a> that queries data against a table whose name is not known until runtime.<\/p>\n\n\n\n<p>Creating a dynamic SQL is simple, you just need to make it a string as follows:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\">'<span class=\"hljs-keyword\">SELECT<\/span> * <span class=\"hljs-keyword\">FROM<\/span> production.products<span class=\"hljs-string\">';\n<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>To execute a dynamic SQL statement, you call the stored procedure <code>sp_executesql<\/code> as shown in the following statement:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\">EXEC sp_executesql N'<span class=\"hljs-keyword\">SELECT<\/span> * <span class=\"hljs-keyword\">FROM<\/span> production.products<span class=\"hljs-string\">';<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Because the <code>sp_executesql<\/code> accepts the dynamic SQL as a Unicode string, you need to prefix it with an <code>N<\/code>.<\/p>\n\n\n\n<p>Though this dynamic SQL is not very useful, it illustrates a dynamic SQL very well.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='using-dynamic-sql-to-query-from-any-table-example'>Using dynamic SQL to query from any table example <a href=\"#using-dynamic-sql-to-query-from-any-table-example\" class=\"anchor\" id=\"using-dynamic-sql-to-query-from-any-table-example\" title=\"Anchor for Using dynamic SQL to query from any table example\">#<\/a><\/h3>\n\n\n\n<p>First, declare two variables, <code>@table<\/code> for holding the name of the table from which you want to query and <code>@sql<\/code> for holding the dynamic SQL.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">DECLARE<\/span> \n    @<span class=\"hljs-keyword\">table<\/span> <span class=\"hljs-keyword\">NVARCHAR<\/span>(<span class=\"hljs-number\">128<\/span>),\n    @<span class=\"hljs-keyword\">sql<\/span> <span class=\"hljs-keyword\">NVARCHAR<\/span>(<span class=\"hljs-keyword\">MAX<\/span>);\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Second, set the value of the <code>@table<\/code>&nbsp;variable to <code>production.products<\/code>.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">SET<\/span> @<span class=\"hljs-keyword\">table<\/span> = N<span class=\"hljs-string\">'production.products'<\/span>;\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Third, construct the dynamic SQL by concatenating the <code>SELECT<\/code> statement with the table name parameter:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">SET<\/span> @<span class=\"hljs-keyword\">sql<\/span> = N<span class=\"hljs-string\">'SELECT * FROM '<\/span> + @<span class=\"hljs-keyword\">table<\/span>;\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Fourth, call the <code>sp_executesql<\/code> stored procedure by passing the <code>@sql<\/code> parameter.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\">EXEC sp_executesql @sql;\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Putting it all together:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">DECLARE<\/span> \n    @<span class=\"hljs-keyword\">table<\/span> <span class=\"hljs-keyword\">NVARCHAR<\/span>(<span class=\"hljs-number\">128<\/span>),\n    @<span class=\"hljs-keyword\">sql<\/span> <span class=\"hljs-keyword\">NVARCHAR<\/span>(<span class=\"hljs-keyword\">MAX<\/span>);\n\n<span class=\"hljs-keyword\">SET<\/span> @<span class=\"hljs-keyword\">table<\/span> = N<span class=\"hljs-string\">'production.products'<\/span>;\n\n<span class=\"hljs-keyword\">SET<\/span> @<span class=\"hljs-keyword\">sql<\/span> = N<span class=\"hljs-string\">'SELECT * FROM '<\/span> + @<span class=\"hljs-keyword\">table<\/span>;\n\nEXEC sp_executesql @sql;\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The code block above produces the exact result set as the following statement:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">SELECT<\/span> * <span class=\"hljs-keyword\">FROM<\/span> production.products;\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>To query data from another table, you change the value of the <code>@table<\/code>&nbsp;variable. However, it&#8217;s more practical if we wrap the above T-SQL block in a stored procedure.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='sql-server-dynamic-sql-and-stored-procedures'>SQL Server dynamic SQL and stored procedures <a href=\"#sql-server-dynamic-sql-and-stored-procedures\" class=\"anchor\" id=\"sql-server-dynamic-sql-and-stored-procedures\" title=\"Anchor for SQL Server dynamic SQL and stored procedures\">#<\/a><\/h3>\n\n\n\n<p>This stored procedure accepts any table and returns the result set from a specified table by using the dynamic SQL:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">CREATE<\/span> PROC usp_query (\n    @<span class=\"hljs-keyword\">table<\/span> <span class=\"hljs-keyword\">NVARCHAR<\/span>(<span class=\"hljs-number\">128<\/span>)\n)\n<span class=\"hljs-keyword\">AS<\/span>\n<span class=\"hljs-keyword\">BEGIN<\/span>\n\n    <span class=\"hljs-keyword\">DECLARE<\/span> @<span class=\"hljs-keyword\">sql<\/span> <span class=\"hljs-keyword\">NVARCHAR<\/span>(<span class=\"hljs-keyword\">MAX<\/span>);\n    <span class=\"hljs-comment\">-- construct SQL<\/span>\n    <span class=\"hljs-keyword\">SET<\/span> @<span class=\"hljs-keyword\">sql<\/span> = N<span class=\"hljs-string\">'SELECT * FROM '<\/span> + @<span class=\"hljs-keyword\">table<\/span>;\n    <span class=\"hljs-comment\">-- execute the SQL<\/span>\n    EXEC sp_executesql @sql;\n    \n<span class=\"hljs-keyword\">END<\/span>;\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The following statement calls the <code>usp_query<\/code>&nbsp;stored procedure to return all rows from the <code>production.brands<\/code> table:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\">EXEC usp_query 'production.brands';\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>This stored procedure returns the top 10 rows from a table by the values of a specified column:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">CREATE<\/span> <span class=\"hljs-keyword\">OR<\/span> <span class=\"hljs-keyword\">ALTER<\/span> PROC usp_query_topn(\n    @<span class=\"hljs-keyword\">table<\/span> <span class=\"hljs-keyword\">NVARCHAR<\/span>(<span class=\"hljs-number\">128<\/span>),\n    @topN <span class=\"hljs-built_in\">INT<\/span>,\n    @byColumn <span class=\"hljs-keyword\">NVARCHAR<\/span>(<span class=\"hljs-number\">128<\/span>)\n)\n<span class=\"hljs-keyword\">AS<\/span>\n<span class=\"hljs-keyword\">BEGIN<\/span>\n    <span class=\"hljs-keyword\">DECLARE<\/span> \n        @<span class=\"hljs-keyword\">sql<\/span> <span class=\"hljs-keyword\">NVARCHAR<\/span>(<span class=\"hljs-keyword\">MAX<\/span>),\n        @topNStr <span class=\"hljs-keyword\">NVARCHAR<\/span>(<span class=\"hljs-keyword\">MAX<\/span>);\n\n    <span class=\"hljs-keyword\">SET<\/span> @topNStr  = <span class=\"hljs-keyword\">CAST<\/span>(@topN <span class=\"hljs-keyword\">as<\/span> <span class=\"hljs-keyword\">nvarchar<\/span>(<span class=\"hljs-keyword\">max<\/span>));\n\n    <span class=\"hljs-comment\">-- construct SQL<\/span>\n    <span class=\"hljs-keyword\">SET<\/span> @<span class=\"hljs-keyword\">sql<\/span> = N<span class=\"hljs-string\">'SELECT TOP '<\/span> +  @topNStr  + \n                <span class=\"hljs-string\">' * FROM '<\/span> + @<span class=\"hljs-keyword\">table<\/span> + \n                    <span class=\"hljs-string\">' ORDER BY '<\/span> + @byColumn + <span class=\"hljs-string\">' DESC'<\/span>;\n    <span class=\"hljs-comment\">-- execute the SQL<\/span>\n    EXEC sp_executesql @sql;\n    \n<span class=\"hljs-keyword\">END<\/span>;\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>For example, you can get the top 10 most expensive products from the <code>production.products<\/code> table:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\">EXEC usp_query_topn \n        'production.products',\n        10, \n        'list_price';\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>This statement returns the top 10 products with the highest quantity in stock:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\">EXEC usp_query_topn \n        'production.tocks',\n        10, \n        'quantity';\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='sql-server-dynamic-sql-and-sql-injection'>SQL Server Dynamic SQL and SQL Injection <a href=\"#sql-server-dynamic-sql-and-sql-injection\" class=\"anchor\" id=\"sql-server-dynamic-sql-and-sql-injection\" title=\"Anchor for SQL Server Dynamic SQL and SQL Injection\">#<\/a><\/h2>\n\n\n\n<p>Let&#8217;s <a href=\"https:\/\/www.sqlservertutorial.net\/sql-server-basics\/sql-server-create-table\/\">create a new table<\/a> named <code>sales.tests<\/code> for the demonstration:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-14\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">CREATE<\/span> <span class=\"hljs-keyword\">TABLE<\/span> sales.tests(<span class=\"hljs-keyword\">id<\/span> <span class=\"hljs-built_in\">INT<\/span>); \n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-14\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>This statement returns all rows from the <code>production.brands<\/code> table:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-15\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\">EXEC usp_query 'production.brands';\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-15\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>But it does not prevent users from passing the table name as follows:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-16\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\">EXEC usp_query 'production.brands;<span class=\"hljs-keyword\">DROP<\/span> <span class=\"hljs-keyword\">TABLE<\/span> sales.tests<span class=\"hljs-string\">';\n<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-16\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>This technique is called SQL injection. Once the statement is executed, the <code>sales.tests<\/code> table is dropped, because the stored procedure <code>usp_query<\/code> executes both statements:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-17\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">SELECT<\/span> * <span class=\"hljs-keyword\">FROM<\/span> production.brands;<span class=\"hljs-keyword\">DROP<\/span> <span class=\"hljs-keyword\">TABLE<\/span> sales.tests\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-17\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>To prevent this SQL injection, you can use the <code><a href=\"https:\/\/www.sqlservertutorial.net\/sql-server-string-functions\/sql-server-quotename-function\/\">QUOTENAME()<\/a><\/code> function as shown in the following query:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-18\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">CREATE<\/span> <span class=\"hljs-keyword\">OR<\/span> <span class=\"hljs-keyword\">ALTER<\/span> PROC usp_query\n(\n    @<span class=\"hljs-keyword\">schema<\/span> <span class=\"hljs-keyword\">NVARCHAR<\/span>(<span class=\"hljs-number\">128<\/span>), \n    @<span class=\"hljs-keyword\">table<\/span>  <span class=\"hljs-keyword\">NVARCHAR<\/span>(<span class=\"hljs-number\">128<\/span>)\n)\n<span class=\"hljs-keyword\">AS<\/span>\n    <span class=\"hljs-keyword\">BEGIN<\/span>\n        <span class=\"hljs-keyword\">DECLARE<\/span> \n            @<span class=\"hljs-keyword\">sql<\/span> <span class=\"hljs-keyword\">NVARCHAR<\/span>(<span class=\"hljs-keyword\">MAX<\/span>);\n        <span class=\"hljs-comment\">-- construct SQL<\/span>\n        <span class=\"hljs-keyword\">SET<\/span> @<span class=\"hljs-keyword\">sql<\/span> = N<span class=\"hljs-string\">'SELECT * FROM '<\/span> \n            + <span class=\"hljs-keyword\">QUOTENAME<\/span>(@<span class=\"hljs-keyword\">schema<\/span>) \n            + <span class=\"hljs-string\">'.'<\/span> \n            + <span class=\"hljs-keyword\">QUOTENAME<\/span>(@<span class=\"hljs-keyword\">table<\/span>);\n        <span class=\"hljs-comment\">-- execute the SQL<\/span>\n        EXEC sp_executesql @sql;\n    <span class=\"hljs-keyword\">END<\/span>;\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-18\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Now, if you pass the schema and table name to the stored procedure, it will work:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-19\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\">EXEC usp_query 'production','brands';\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-19\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>However, if you try to inject another statement such as:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-20\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\">EXEC usp_query \n        'production',\n        'brands;<span class=\"hljs-keyword\">DROP<\/span> <span class=\"hljs-keyword\">TABLE<\/span> sales.tests<span class=\"hljs-string\">';\n<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-20\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>It will issue the following error:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-21\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\">Invalid object name 'production.brands;<span class=\"hljs-keyword\">DROP<\/span> <span class=\"hljs-keyword\">TABLE<\/span> sales.tests<span class=\"hljs-string\">'.\n<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-21\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='more-on-sp_executesql-stored-procedure'>More on sp_executesql stored procedure <a href=\"#more-on-sp_executesql-stored-procedure\" class=\"anchor\" id=\"more-on-sp_executesql-stored-procedure\" title=\"Anchor for More on &lt;code&gt;sp_executesql&lt;\/code&gt; stored procedure\">#<\/a><\/h2>\n\n\n\n<p>The <code>sp_executesql<\/code> has the following syntax:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-22\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\">EXEC sp_executesql \n    sql_statement  \n    parameter_definition\n    @param1 = value1,\n    @param2 = value2,\n    ...\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-22\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this syntax:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>sql_statement<\/code> is a Unicode string that contains a T-SQL statement. The <code>sql_statement<\/code> can contain parameters such as <code>SELECT * FROM table_name WHERE id=@id<\/code><\/li><li><code>parameter_definition<\/code> is a string that contains the definition of all parameters embedded in the <code>sql_statement<\/code>. Each parameter definition consists of a parameter name and its data type e.g., <code>@id INT<\/code>. The parameter definitions are separated by a comma (,).<\/li><li><code>@param1 = value1<\/code>, <code>@param2 = value2<\/code>,&#8230; specify a value for every parameter defined in the <code>parameter_definition<\/code> string.<\/li><\/ul>\n\n\n\n<p>This example uses the <code>sp_executesql<\/code> stored procedure to find products which have list price greater than 100 and category 1:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-23\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\">EXEC sp_executesql\nN'<span class=\"hljs-keyword\">SELECT<\/span> *\n    <span class=\"hljs-keyword\">FROM<\/span> \n        production.products \n    <span class=\"hljs-keyword\">WHERE<\/span> \n        list_price&gt; @listPrice <span class=\"hljs-keyword\">AND<\/span>\n        category_id = @categoryId\n    <span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span>\n        list_price <span class=\"hljs-keyword\">DESC<\/span><span class=\"hljs-string\">', \nN'<\/span>@listPrice <span class=\"hljs-built_in\">DECIMAL<\/span>(<span class=\"hljs-number\">10<\/span>,<span class=\"hljs-number\">2<\/span>),\n@categoryId <span class=\"hljs-built_in\">INT<\/span><span class=\"hljs-string\">'\n,@listPrice = 100\n,@categoryId = 1;\n<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-23\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this tutorial, you have learned how to use the SQL Server dynamic SQL to construct general purpose and flexible SQL statements.<\/p>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"1741\"\n\t\t\t\tdata-post-url=\"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-dynamic-sql\/\"\n\t\t\t\tdata-post-title=\"SQL Server Dynamic SQL\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"1741\"\n\t\t\t\tdata-post-url=\"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-dynamic-sql\/\"\n\t\t\t\tdata-post-title=\"SQL Server Dynamic SQL\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\n\t\t\t<button class=\"btn btn-primary wth-btn-submit\">Send<\/button>\n\t\t\t<button class=\"btn wth-btn-cancel\">Cancel<\/button>\n\t\t\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you will learn how to use the SQL Server dynamic SQL to construct general purpose and flexible SQL statements.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":777,"menu_order":13,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1741","page","type-page","status-publish","hentry"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.5 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>SQL Server Dynamic SQL<\/title>\n<meta name=\"description\" content=\"This tutorial shows you how to use the SQL Server dynamic SQL to construct general purpose and flexible SQL statements.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-dynamic-sql\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"SQL Server Dynamic SQL\" \/>\n<meta property=\"og:description\" content=\"This tutorial shows you how to use the SQL Server dynamic SQL to construct general purpose and flexible SQL statements.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-dynamic-sql\/\" \/>\n<meta property=\"og:site_name\" content=\"SQL Server Tutorial\" \/>\n<meta property=\"article:modified_time\" content=\"2020-04-11T13:12:27+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/sql-server-stored-procedures\\\/sql-server-dynamic-sql\\\/\",\"url\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/sql-server-stored-procedures\\\/sql-server-dynamic-sql\\\/\",\"name\":\"SQL Server Dynamic SQL\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/#website\"},\"datePublished\":\"2019-04-15T13:23:40+00:00\",\"dateModified\":\"2020-04-11T13:12:27+00:00\",\"description\":\"This tutorial shows you how to use the SQL Server dynamic SQL to construct general purpose and flexible SQL statements.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/sql-server-stored-procedures\\\/sql-server-dynamic-sql\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.sqlservertutorial.net\\\/sql-server-stored-procedures\\\/sql-server-dynamic-sql\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/sql-server-stored-procedures\\\/sql-server-dynamic-sql\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"SQL Server Stored Procedures\",\"item\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/sql-server-stored-procedures\\\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"SQL Server Dynamic SQL\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/#website\",\"url\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/\",\"name\":\"SQL Server Tutorial\",\"description\":\"The Practical SQL Server Tutorial\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"SQL Server Dynamic SQL","description":"This tutorial shows you how to use the SQL Server dynamic SQL to construct general purpose and flexible SQL statements.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-dynamic-sql\/","og_locale":"en_US","og_type":"article","og_title":"SQL Server Dynamic SQL","og_description":"This tutorial shows you how to use the SQL Server dynamic SQL to construct general purpose and flexible SQL statements.","og_url":"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-dynamic-sql\/","og_site_name":"SQL Server Tutorial","article_modified_time":"2020-04-11T13:12:27+00:00","twitter_card":"summary_large_image","twitter_misc":{"Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-dynamic-sql\/","url":"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-dynamic-sql\/","name":"SQL Server Dynamic SQL","isPartOf":{"@id":"https:\/\/www.sqlservertutorial.net\/#website"},"datePublished":"2019-04-15T13:23:40+00:00","dateModified":"2020-04-11T13:12:27+00:00","description":"This tutorial shows you how to use the SQL Server dynamic SQL to construct general purpose and flexible SQL statements.","breadcrumb":{"@id":"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-dynamic-sql\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-dynamic-sql\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-dynamic-sql\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.sqlservertutorial.net\/"},{"@type":"ListItem","position":2,"name":"SQL Server Stored Procedures","item":"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/"},{"@type":"ListItem","position":3,"name":"SQL Server Dynamic SQL"}]},{"@type":"WebSite","@id":"https:\/\/www.sqlservertutorial.net\/#website","url":"https:\/\/www.sqlservertutorial.net\/","name":"SQL Server Tutorial","description":"The Practical SQL Server Tutorial","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.sqlservertutorial.net\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"}]}},"_links":{"self":[{"href":"https:\/\/www.sqlservertutorial.net\/wp-json\/wp\/v2\/pages\/1741","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.sqlservertutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.sqlservertutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.sqlservertutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.sqlservertutorial.net\/wp-json\/wp\/v2\/comments?post=1741"}],"version-history":[{"count":0,"href":"https:\/\/www.sqlservertutorial.net\/wp-json\/wp\/v2\/pages\/1741\/revisions"}],"up":[{"embeddable":true,"href":"https:\/\/www.sqlservertutorial.net\/wp-json\/wp\/v2\/pages\/777"}],"wp:attachment":[{"href":"https:\/\/www.sqlservertutorial.net\/wp-json\/wp\/v2\/media?parent=1741"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}