{"id":18312,"date":"2022-11-04T07:05:00","date_gmt":"2022-11-04T06:05:00","guid":{"rendered":"https:\/\/expert-only.com\/?p=18312"},"modified":"2022-11-21T12:25:50","modified_gmt":"2022-11-21T11:25:50","slug":"t-sql-procedure-with-hard-coded-variables","status":"publish","type":"post","link":"https:\/\/expert-only.com\/en\/t-sql\/t-sql-procedure-with-hard-coded-variables\/","title":{"rendered":"T-SQL procedure with hard coded variables and  dynamic execution"},"content":{"rendered":"\n<h4 class=\"has-text-align-center wp-block-heading\" id=\"h-how-to-execute-a-t-sql-procedure-from-a-text-with-a-hard-coded-variable\"><strong><em>How to execute a T-SQL procedure from a text with a hard coded variable?<\/em><\/strong><\/h4>\n\n\n\n<p>Tutorial to manage and execute a T-SQL procedure with hard coded variables, i.e. stored in a string. Indeed, a normal execution does not work with the EXEC command alone. So how do you get around this error? The solution to the problem is to use the T-SQL EXEC function sp_executesql.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">1. How to execute a T-SQL procedure with hard coded variables ?<\/h2>\n\n\n\n<p>n fact, here is an example of code to execute a string in T-SQL with the command in a variable that itself contains a hard-coded variable in the text. First, create the customer table to insert the data as in the example below. The goal is to build and execute a dynamic query of this type:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"mssql\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">DECLARE @VARIABLE AS NVARCHAR(100);\nDECLARE @SQL AS NVARCHAR(400); \n\nSET @VARIABLE = 'Test'\nSET @SQL = 'SELECT FIELD1, FIELD2 FROM TABLE_1 WHERE FIELD1 = @VARIABLE';\n\nPRINT @SQL;\n\nEXEC @SQL;<\/pre>\n\n\n\n<p>Then the following error occurs:<\/p>\n\n\n\n<p><em>Could not find stored procedure &#8216;SELECT FIELD1, FIELD2 FROM TABLE_1 WHERE FIELD1 = @VARIABLE&#8217;.<\/em><\/p>\n\n\n\n<p>And with another variant using a different script. This script includes the declaration, the instanciation and the usage of the variable in the same variable, to execute.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"mssql\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">DECLARE @SQL_To_Execute AS NVARCHAR(800); \n\nSET @SQL_To_Execute = '\nDECLARE @VARIABLE AS NVARCHAR(100) = ''Test'';\nDECLARE @SQL AS NVARCHAR(400) = \n'' SELECT FIELD1, FIELD2 FROM TABLE_1 WHERE FIELD1 = @VARIABLE '';\n';\n\nEXEC  @SQL_To_Execute; <\/pre>\n\n\n\n<p>The following error message is displayed:<\/p>\n\n\n\n<p><em>The name &#8216;<br>DECLARE @VARIABLE AS NVARCHAR(100) = &#8216;Test&#8217;;<br>DECLARE @SQL AS NVARCHAR(400) =<br>&#8216; SELECT FIELD1, FIELD2 FROM TABLE_1 WHERE FIELD1 = @VARIABLE &#8216;;<br>&#8216; is not a valid identifier.<\/em><\/p>\n\n\n\n<p>Or in other cases, this error can also be encountered: <\/p>\n\n\n\n<p><em>Must declare the scalar variable &#8221; @SQL&#8221; .<\/em><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">2. Create the sample table used in the T-SQL procedure<\/h2>\n\n\n\n<p>The first step is to create a customer&#8217;s table, used in the stored procedure script.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"mssql\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">-- Test if the table CUSTOMERS already exists\n-- And delete it if necessary\nIF EXISTS(\n   SELECT 1 FROM sys.objects\n   WHERE  object_id = object_id(N'[dbo].[CUSTOMERS]')\n      AND type in (N'U')\n)\nDROP TABLE [dbo].[CUSTOMERS]\nGO\n\n-- Create the CUSTOMERS table with the column NAME declared as UNIQUE\n-- The UNIQUE keyword defines the column with a unique value\n-- Inserting two customers with the same name is therefore impossible\nCREATE TABLE [dbo].[CUSTOMERS] (\n   [CLIENTID] int IDENTITY(1,1),\n   [NAME] nvarchar(20) UNIQUE,\n   [CITY] nvarchar(20)\n)\nGO\n\n-- Insert data for manipulation examples\nINSERT INTO dbo.CUSTOMERS (NAME, CITY) VALUES ('MAMMADOU', 'Lyon');\nINSERT INTO dbo.CUSTOMERS (NAME, CITY) VALUES ('SERGEI', 'Lyon');\nINSERT INTO dbo.CUSTOMERS (NAME, CITY) VALUES ('CHRISTOPHE', 'Paris');\n\n-- Check inserted rows\nSELECT    *\nFROM    dbo.CUSTOMERS;<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">3. Avoid SQL Server errors with dynamic T-SQL code and variables<\/h2>\n\n\n\n<p>Here is the solution in T-SQL to execute a SQL Server query with a variable. Build in several steps, if necessary, include them in a stored procedure. Now let&#8217;s build a fully dynamic stored procedure, that passes the hard coded variable into the text to run:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Declaration of the variables<\/strong> used, such as the counter for the loop, and the variable with a string, parameters, etc.<\/li>\n\n\n\n<li><strong>Build the loop<\/strong> for each of the counter values.<\/li>\n\n\n\n<li><strong>Execute the query<\/strong> to insert data inside the loop<\/li>\n\n\n\n<li><strong>Display the counter value<\/strong> for each iteration<\/li>\n<\/ul>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"mssql\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">-- Declare the variables used in the stored procedure.\n-- The counter\n-- The variable for the name of the customer\n-- The variable for the city name\n-- The parameter string is used to declare the variables\n-- The SQL string is in this case a query to insert rows\nDECLARE @Counter INT;  \t\nDECLARE @CustomerName NVARCHAR(20);  \nDECLARE @CustomerCity NVARCHAR(20);  \nDECLARE @Parameters NVARCHAR(100);  \nDECLARE @SQL_To_Execute NVARCHAR(200);\n\n-- Declare a hard-coded string in the @Parameters variable\nSET @Parameters =\n '@CustomerName NVARCHAR(20),@CustomerCity NVARCHAR(20)';\n\n-- Build a basic T-SQL Insert query with a dynamic member\nSET @SQL_To_Execute = \n 'INSERT INTO [dbo].[CUSTOMERS] VALUES (@CustomerName,@CustomerCity)';\n\n-- Beginning of the loop\nSET @Counter = 0 \nWHILE @Counter &lt; 8\n  BEGIN\n    SET @Counter = @Counter + 1\n    SET @CustomerName = 'Name-' + CAST(@Counter AS CHAR);\n    SET @CustomerCity = 'City-' + CAST(@Counter AS CHAR);\n    \n    -- Run the query with the parameters\n    EXEC  sp_executesql @SQL_To_Execute,@Parameters, @CustomerName,@CustomerCity;\n    \n    PRINT  'Counter current value is : ' + CAST(@Counter AS CHAR)\n  END\n-- End of the loop\n<\/pre>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"810\" height=\"740\" src=\"https:\/\/expert-only.com\/wp-content\/uploads\/2022\/11\/t-sql-procedure-with-hard-coded-variables.jpg\" alt=\"Execute a T-SQL procedure with hard coded variables\" class=\"wp-image-18327\" srcset=\"https:\/\/expert-only.com\/wp-content\/uploads\/2022\/11\/t-sql-procedure-with-hard-coded-variables.jpg 810w, https:\/\/expert-only.com\/wp-content\/uploads\/2022\/11\/t-sql-procedure-with-hard-coded-variables-300x274.jpg 300w, https:\/\/expert-only.com\/wp-content\/uploads\/2022\/11\/t-sql-procedure-with-hard-coded-variables-768x702.jpg 768w\" sizes=\"auto, (max-width: 810px) 100vw, 810px\" \/><figcaption class=\"wp-element-caption\"><strong>Execute a T-SQL procedure with hard coded variables using sp_executesql<\/strong><\/figcaption><\/figure>\n<\/div>\n\n\n<p>Finally display the results of the data insertion with a simple SQL Server SELECT query.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"mssql\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">SELECT *\nFROM [dbo].[CUSTOMERS];\n<\/pre>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"640\" height=\"400\" src=\"https:\/\/expert-only.com\/wp-content\/uploads\/2022\/11\/t-sql-procedure-with-hard-coded-variables-select-data.jpg\" alt=\"Select the data inserted with the dynamic T-SQL stored procedure\" class=\"wp-image-18335\" srcset=\"https:\/\/expert-only.com\/wp-content\/uploads\/2022\/11\/t-sql-procedure-with-hard-coded-variables-select-data.jpg 640w, https:\/\/expert-only.com\/wp-content\/uploads\/2022\/11\/t-sql-procedure-with-hard-coded-variables-select-data-300x188.jpg 300w\" sizes=\"auto, (max-width: 640px) 100vw, 640px\" \/><figcaption class=\"wp-element-caption\">Select the data inserted with the dynamic T-SQL stored procedure<\/figcaption><\/figure>\n<\/div>\n\n\n<h2 class=\"wp-block-heading\">4. Benefits of sp_executesql function with hard-coded variables<\/h2>\n\n\n\n<p>Finally, use the EXEC <a href=\"https:\/\/renenyffenegger.ch\/notes\/development\/databases\/SQL-Server\/administration\/schemas\/sys\/objects\/stored-procedures\/sp_executesql\" target=\"_blank\" rel=\"noreferrer noopener\">sp_executesql<\/a> function instead of EXECUTE. This procedure generates reusable execution plans during loop executions. This way, performance is improved. Using this function is very useful for a complex query that is executed a significant number of times.<\/p>\n\n\n\n<p>This method allows you to generate particularly dynamic code and thus execute a query with a variable in T-SQL that is replaced on the fly during code execution. After this article with an example to execute T-SQL procedure with hard coded variables. Below are more tutorials, like how to manage SQL Server fields of more than 8000 characters. Or an article to split a string with semicolon separators.<\/p>\n\n\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-sql-and-it-tutorials wp-block-embed-sql-and-it-tutorials\"><div class=\"wp-block-embed__wrapper\">\nhttps:\/\/expert-only.com\/en\/t-sql\/sql-server-text-with-more-than-8000-characters\/\n<\/div><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Tutorials on SQL Server stored procedures and T-SQL<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/expert-only.com\/en\/t-sql\/execute-sql-server-procedure-with-parameters\/\">Execute a SQL Server stored procedure with parameters<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/expert-only.com\/en\/t-sql\/sql-server-text-with-more-than-8000-characters\/\">Managing SQL Server text fields longer than 8000 characters<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/expert-only.com\/en\/t-sql\/return-values-sql-server-stored-procedure\/\">How to return values with SQL Server stored procedure?<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/expert-only.com\/en\/t-sql\/split-a-string-after-a-character\/\">Split a string after a character with SQL Server<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<div class=\"mh-excerpt\"><p>How to execute a T-SQL procedure from a text with a hard coded variable? Tutorial to manage and execute a T-SQL procedure with hard coded variables, i.e. stored in a string. Indeed, a normal execution does not work with <a class=\"mh-excerpt-more\" href=\"https:\/\/expert-only.com\/en\/t-sql\/t-sql-procedure-with-hard-coded-variables\/\" title=\"T-SQL procedure with hard coded variables and  dynamic execution\">&#8230;<\/a><\/p>\n<\/div>","protected":false},"author":1,"featured_media":10544,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[454],"tags":[],"class_list":{"0":"post-18312","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-t-sql"},"_links":{"self":[{"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/posts\/18312","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/comments?post=18312"}],"version-history":[{"count":0,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/posts\/18312\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/media\/10544"}],"wp:attachment":[{"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/media?parent=18312"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/categories?post=18312"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/tags?post=18312"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}