My stored procedure has to allow user of the branch office to grab the data pertaining to the branch location, SELECTLAST_NAME, FIRST_NAMEFROM HAMMOND.dbo.PERSON WHERE POSTAL_CODE = '12345', SELECT LAST_NAME, FIRST_NAME FROM ROCKVILLE.dbo.PERSON WHERE POSTAL_CODE = '98765', WHERE POSTAL_CODE = '''[emailprotected]+''''. sql-server dynamic sql-server-2008-r2 exec. rev2023.3.3.43278. Given below is the script. much do whatever you need to in order to construct the statement. of this, sometimes there is a need to dynamically create a SQL statement on the fly [' + @Grouping + ']. As you can see from this Dynamic SQL query example handling the @city value is not at straight You must Break those Strings up or SQL Server will Truncate each one BEFORE concatenating. Worked like a charm for me. Problems redirecting to dynamic URLs in Flask with 'action' NodeJS fetch is returning more data than it should, and it's not the data my Flask server is sending it; Socketio client switching to xhr-polling running with flask app; Stop a background process in flask without creating zombie processes; Flask: issue remains even after enabling CORS So put all your data in @SQLString variable and execute like below: Thanks for contributing an answer to Stack Overflow! Let's say we want When concatenating long strings (or strings that you feel could be long) always pre-concatenate your string building with CAST('' as nVarChar(MAX)) like so: What a pain and scary to think this is just how SQL Server works. 2- (This is what I did at first) Check THIS post: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=52274 and do what user "Kristen" says. so the question is, how are you determining the string is only 8000; most likely the string is certainly bigger, is stored in a complete fashion, but something you are using to display the data is limiting it to 8000 characters. How can I get column names from a table in SQL Server? With the Execute Statement you are building the SQL statement on the fly and can pretty Like '@string = N'SELECT * FROM Table', Dynamic SQL Script More Than 8000 Characters, How Intuit democratizes AI development across teams through reusability. I wisht to fetch out the total record count from the Table. [Stores2 Sales Quantity]), MEMBER [Measures]. http://technet.microsoft.com/en-us/library/ms178642.aspx. [Shop by Model].[Brand].&[7FAM].&[Outlet].&[0ZW],[Shop]. being built. In the right side panel choose Results To Text option from the Default destination for results drop down list. Not the answer you're looking for? Thanks a lot:), SET @sql1 = 'Select * into #temp1 from OPENQUERY(Lkremote, '+@sqlquery+')'. [CountryRank] AS Rank(iif("' + @Grouping + '"="Lot" or "' + @Grouping + '"="Style",([Shop]. Try this. Find centralized, trusted content and collaborate around the technologies you use most. As we said before, usually, the issue can occur when you are trying to make a query dynamically and if the length exceeds 4000 characters ( a variable of type nvarchar) or 8000 ( in case of varchar). Arun and he wanted to store more than 8,000 characters in a column. [All], ' + @ArticleFilter + '), [Articles]. Should you identify any content that is harmful, malicious, sensitive or unnecessary, please contact me via email (imran@raresql.com) so I may rectify the problem. The error could be from the actual execution of the SQL itself and not related to EXECUTE IMMEDIATE or DBMS_SQL Azadare M Member Posts: 350 Jun 18, 2013 2:37AM Have tried this: Making statements based on opinion; back them up with references or personal experience. The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie We've added a "Necessary cookies only" option to the cookie consent popup. INSERT INTO #temp SELECT DISTINCT CONVERT (smalldatetime, AttendanceDate, 103) AS Pivot FROM dbo.vw_ARS_StudentClassAttendance WHERE RegisterID = @RegisterID . and then run that command. [CountryCOGS] AS ([Measures]. you have to use the new sys.sp_sqlexec stored proc that accepts a parameter of type text. I can't believe this is sooo hard to figure out. Always remember that anything called by EXEC statement is executed in a separated session. [Country Group].CURRENTMEMBER.MEMBER_CAPTION,[Shop]. Pero mas adentro en un procedimiento secundario no funciona y se queda el equipo ejecutando la consulta indefinidamente. But perhaps I'm misremembering, and the formatting is preserved once you copy the text from the grid (or run it in text mode). To prevent this you should convert it to (N)VARCHAR(MAX), You should read the answer of this post which explains extremely well the situation : DECLARE @StartDate AS VARCHAR(10), @SQL NVARCHAR(MAX); SET @StartDate = '01-JAN-19'; SET @SQL = 'SELECT * FROM OPENQUERY(XREF_PROD, ''SELECT leavetype, leavereason FROM XREF.XREF_CALENDER WHERE createdon >= ''''' + @StartDate + ''''''')'; EXEC sp_executesql @SQL; I need to take this result now and INSERT it into table on sql server. For fast, accurate and documented assistance in answering your questions, please read this article.Understanding and using APPLY, (I) and (II) Paul WhiteHidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden, NVARCHAR(MAX) supports a huge string 2^31 - 1 bytes(~1+gig nvarchars )however, many applications, specifically SQL Server Management Studio, will only display the first 8000 characters of the string no matter what the value is, so if the data is stored in a varchar(max)/nvarchar(max), it defaults to display only the first 256 characters, but if you change the setting pictured below to a largest value, it still will only display the first 8K chars(this is for performance reasons, so grids don't freeze up). http://www.dpriver.com/pp/sqlformat.htm?ref=g_wangz, Thank you,Jeremy KadlecCommunity Co-Leader, lets say i have written a stored procedure.Later i realized that some of keywords within the stored proc are in upper case and some in lower case,now to give it a standard look i want to change all the lowercase keywords into uppercase.For that i need a query or stored proc.I was trying but couldn't find out how to get all the keywords used within a stored proc.Would be very thankfull if you could help me :-), i want to execute this SQL command:select * from CountryName where countryName like 's%'. You're in the best position to judge because its your data. Unlike OPENQUERY EXEC() can accept a query as a variable and that variable can be declared as a MAX datatype. [Stores2 Sales Cost - Base], [Articles]. [' + @Grouping + '] * [Articles].[Season]. [' + @Grouping + ']. Using indicator constraint with two variables, Linear Algebra - Linear transformation question. thank u. Hi Raghu Iyer, you can use a WHILE loop to process through multiple items. Good question/answer about nvarchat/varchar, To explicitly say to system that this is nvarchar put N before single quoted expression. If that truly is dynamic SQL, then every stored procedure I've ever written is done using dynamic SQL (okay, maybe 95%, since perhaps I've written a few that don't have parameters. I learned that you can execute the sp_executesql statement multiple times. But to use this way, the datatype and number of variable that to be used at a run time need to be known before. By clicking Post Your Answer, you agree to our terms of service, privacy policy and cookie policy. You can't create a NVARCHAR (8000). [Shop by Model].[Brand].&[7FAM].&[Retail].&[0D7],[Shop]. However, I am usually executing multiple "commands", not 1 single command greater than 8000 chars. How to execute a long dynamic query (greater than 4000) characters - again. We tried the query as suggested but gettting following error: "Msg 7390, Level 16, State 2, Line 153 The requested operation could not be performed because OLE DB provider "MSOLAP" for linked server "OLAP" does not support the required transaction interface.". To subscribe to this RSS feed, copy and paste this URL into your RSS reader. get the query to build correctly. Executing Dynamic SQL larger than 8000 characters Hope this helps you. up other areas of concern such as. Step 3 : Data Model and a Brief Introduction I just discovered another benefit of using sp_executesql to execute the dynamic SQL. the above, here are some other articles that give you other perspectives on Read the complete thread in MSDN forum ! [Shop by Model].[Brand].&[7FAM].&[Retail].&[0BJ],[Shop]. Updated 9-Sep-10 1:54am v2 . Find centralized, trusted content and collaborate around the technologies you use most. You better use SELECT statement, then copy from select and paste into the new query window. [Stores2 Sales Value Net exc VAT - Base]),[Articles]. Do new devs get fired if they can't solve a certain bug? The storage size, in bytes, is two times the number of characters entered + 2 bytes. [Units] AS [Measures]. [TransactionStatus].[Transactionstatus].&[0]. [Shop Model] AS Iif("'+ @DetailLevel +'"= "C",[Shop]. Let me explain the solution step by step. [Shop by Model].[Brand].&[7FAM].&[Retail].&[0BF],[Shop]. It's because that query has some local variables and temporary tables. [Shop by Model].[Brand].&[7FAM].&[Retail].&[0DA],[Shop]. characters. . Another issue is the possible performance issues by generating the code on Each DB has the same set of table names, e.g. [Stores2 Sales Cost - Base],[Articles]. [All],' + @ArticleFilter + ',[Time]. These extra quotes could also be done within the statement, Literal Strings are those you hard-code and wrap in apostrophe's. strQuery = "SELECT tblAppointments.AppID, tblAppointments.AppointDate, tblAppointments.AppointTime, Left([tblSchedule]. Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2. It is just to display the string of 8000 Char but actually my MDX query is making string > 8000 char because of this it does not allow link server to execute MDX query on Analysis server (You can see more detail on previous response). I have been having the same problem, with the strings being truncated. e.g. How to print more than 8,000 characters at a time to the SSMS Message window, without compromising text formatting? This makes a dynamic SQL more flexible as it is not hardcoded. you start to manipulate the overall query string. Declare @Month Int = 1Declare @test2 Nvarchar(255) ='', set @test2 = @MonthSelect @test2 = (Case @test2When 1 then 'December'When 2 then 'January'When 3 then 'February'When 4 then 'March'When 5 then 'April'When 6 then 'May'When 7 then 'June'When 8 then 'July'When 9 then 'August'When 10 then 'September'When 11 then 'October'When 12 then 'November'elseNULL end )Declare @test1 Nvarchar(255) = @Test2+'_AvgNetP'Declare @test3 Nvarchar(255) = @Test2+'_AvgROS'Declare @Select nvarchar(1000) Declare @Select2 nvarchar(1000), Set @Select = 'Select Hdl_Nr,' + @test1 + ',' + @test3 + ' from [Table1] as T'print @select, set @Select2 = 'update t2 set t2.ROS_S = t1.' Looks like I have several options here. If you are on SQL Server 2008 or newer you can use VARCHAR(MAX), Problem is because your string has limit 8000 symbols by default. setting up and using dynamic SQL functionality in your T-SQL code: looks like you cannot pass in a parameter that way for that clause. Change), You are commenting using your Twitter account. But the operand of the "where" clause must be a parameter. They hold places in the SQL statement for actual host variables. [Store Transaction Motive].&[U-]}, [Store Transaction Suspended]. The goal is to provide an alternative that will return the same results as your current query. Puede ser un error mio al colocar la instruccion. SELECT TOP 1 [EmployeeKey],[ParentEmployeeKey],[EmployeeNationalIDAlternateKey],[ParentEmployeeNationalIDAlternateKey], ,[SalesTerritoryKey],[FirstName],[LastName],[MiddleName],[NameStyle],[Title],[HireDate],[BirthDate],[LoginID], ,[EmailAddress],[Phone],[MaritalStatus],[EmergencyContactName],[EmergencyContactPhone],[SalariedFlag], ,[Gender],[PayFrequency],[BaseRate],[VacationHours],[SickLeaveHours],[CurrentFlag],[SalesPersonFlag], ,[DepartmentName],[StartDate],[EndDate],[Status], SET @sql1 = 'Select * INTO #temp1 from OPENQUERY(lmremote, '''+@Query+''')', *******************************************************************. in our case, this sql query is located in the SP which we can't control the the table structure. LAST_NAME, FIRST_NAME, POSTAL_CODE. Long Aug 23 '17 at 17:00. AdventureWorks database for the below examples. This works perfectly fine on the management studio. Is it possible to create a concave light? One issue is the potential for Thanks for all the help. [Stores2 Sales Value Net inc VAT - Base],[Measures]. To run a dynamic SQL statement, run the stored procedure sp_executesql as shown below : Use prefix N with the sp_executesql to use dynamic SQL as a Unicode string. My query is 8621 chars long I broke the query into twoVARCHAR(8000) variables, one was 7900 and the other was 721. I know other workarounds on the web say to break up your code into multiple SET/SELECT assignments using multiple variables, but this is unnecessary given the solution above. On 64-bit servers, the size of the string is limited to 2 GB, the maximum size of nvarchar(max). Ithink that Dynamic SQL is the solution, but we consider this one not enough "elegant" (and the Sql injection issue too), Hi Manish, How do I get your sql command as a output to the other stored procedure. When character expressions are converted to a character data type of a different size, values that are too long for the new data type are truncated. EXECUTE (@SQLString) DECLARE @SQLString varchar (10000) How increase Nvarchar size in SQL? :( [Transactiontype].&[D]), MEMBER [Measures]. [COGS] AS [Measures]. now, I would like to call that procedure multiple times for all the BP_Code ina list. @Manish Kumar - here is simple code to do this: create table #temp (sqlcommand varchar(500))insert into #tempselect 'drop table AccountID_55406' union allselect 'drop table Accountid_70625', DECLARE db_cursor CURSOR FOR SELECT sqlcommand FROM #temp ORDER BY 1, OPEN db_cursor FETCH NEXT FROM db_cursor INTO @sqlcommand, WHILE @@FETCH_STATUS = 0 BEGIN PRINT @sqlcommand EXEC (@sqlcommand) FETCH NEXT FROM db_cursor INTO @sqlcommand END. DECLARE @sqlquery VARCHAR(MAX) = 'SELECT 1 as id, ''hello'' as column1;'; There are no special teachers of virtue, because virtue is taught by the whole community.--Plato. DECLARE @Result DECIMAL(12,2) Next steps For recommendations on using Azure Synapse, see the Cheat Sheet. Transact-SQL syntax conventions Syntax syntaxsql '; your solution is very simpe and usefulI like ir so much. With the EXEC sp_executesql approach you have the ability to still Thanks a lot. Poorly Performing Dynamic SQL Used in SP_EXECUTESQL. [TopSellersUnits]AS Sum(TopSellers,[Measures]. That could easily be missed. document.getElementById( "ak_js_1" ).setAttribute( "value", ( new Date() ).getTime() ); Enter your email address to follow this blog and receive notifications of new posts by email. Execute dynamic generate SQL with length > 8000 . its return 0 rows affected. the query itself is changing based on parameters that are being passed to it--such as the source table in the FROM clause changes based on whether you are pulling data from US or UK), then building the code in a stored procedure, and executing it using sp_executesql is by far the safest way of building and executing your code. [Shop by Model].[Brand].&[7FAM].&[Retail].&[0BA],[Shop]. I think you will find that this will be impossible to manage. To represent a dynamic SQL statement, a character string must contain the text of a valid DML or DDL SQL statement, but not contain the EXEC SQL clause, host-language delimiter or statement terminator.. He construido unos procedimientos almacenados en el motor que interpretan esta formula y la convierten a numeros quedando de la siguiente forma :983.14 - 2*(15.5) +1. Try using use nvarchar (max) - Simon Aug 23 '17 at 16:59. [Stores2 Sales Value Net inc VAT - Base],[Measures]. From that post: This very simple procedure is designed to overcome the limitation in Copyright (c) 2006-2023 Edgewood Solutions, LLC All rights reserved How to count more than one time with different conditions? And when execute it using: I try using replicate and get same problem. Why do we calculate the second half of frequencies in DFT? Ooopps It only inserted 8000 characters even though I passed 10,000. For some reason. Mil Gracias por tu ayuda y abrazos desde medellin, colombia. [Shop by Model]. statements, it does have some drawbacks. I don't know how, but the Execute statement is now working. Developers can use dynamic SQL to construct and run SQL queries at run time as a string, using some logic in SQL to construct varying query strings, without having to pre-construct them during development. En el SSMS funciona. I've split it into 2 variables both declared as varchar (8000) I am able to successfully concatenate them into a large variable declared as nvarchar (MAX). check out this Transact-SQL tutorial. If you have Unicode/nChar/nVarChar values you are concatenating, then SQL Server will implicitly convert your string to VarChar(8000), and it is unfortunately too dumb to realize it will truncate your string or even give you a Warning that data has been truncated for that matter! There @Len should be 8000, as this is the maximum length Management Studio shows. [Shop].members,strtoset("{'+ @Stores +'}")), [Measures]. So if you are dealing with a string of say 80,000 characters. However, that did not work either. Not the answer you're looking for? Really appreciated if you can share anything. In some applications, having hard coded SQL statements is not appealing because Hi, I tried your suggestion to use the NVARCHAR (max) to hold the MDX query of more than 8000 chars (upto 2GB) and also changed data type of parameters passing . If you still have problems, be sure to include all of the non-working code in your new question since there's not enough information help much. Connect and share knowledge within a single location that is structured and easy to search. How do/should administrators estimate the cost of producing an online introductory mathematics class? So I suggested him to use VARCHAR (MAX). Generally the length of a varchar(Max) data type consider it as a 8000 characters and above. [' + @Grouping + ']. In my last tip, I showed how to use T-SQL to generate HTML for fancy calendar visuals overlaid with event data from another table.As an extension of that tip, let's now look at simplifying parts of that query by caching the date information in a calendar table to streamline the outer queries and avoid complications caused by different DATEFIRST settings. I try using replicate and get same problem. What's happening behind the scenes is that even though the variable you are assigning to uses (MAX), SQL Server will evaluate the right-hand side of the value you are assigning first and default to nVarChar(4000) or VarChar(8000) (depending on what you're concatenating). [Stores2 History Inventory Physical Quantity], [Articles]. the following example shows. How do you get out of a corner when plotting yourself into a corner. Most probably the recommended solution would also help to maintain and troubleshoot How to get fast answers to your question[/url] How to post performance related questions[/url]Links for Tally Table [/url] , Cross Tabs [/url] and Dynamic Cross Tabs [/url], Delimited Split Function[/url]. Making statements based on opinion; back them up with references or personal experience. Difficulties with estimation of epsilon-delta limit proof, How to tell which packages are held back due to phased updates, Recovering from a blunder I made while emailing a professor. Step 1 : En el Proc B esta este bloque de instrucciones. CREATE TABLE #temp ( [name] [sysname] NOT NULL, [object_id] [int] NOT NULL ), EXEC ('INSERT INTO #temp SELECT name, object_id FROM sys.objects'). Busca trabajos relacionados con Cdbcommand failed execute sql statement sqlstate 23000 integrity o contrata en el mercado de freelancing ms grande del mundo con ms de 22m de trabajos. [Shop by Model].[Brand].&[VANS].&[Outlet].&[0SG],[Shop]. SQL Server DBMS. [Transactiontype].&[D]), MEMBER [Measures]. So once again, you should make sure While the length of the . [' + @Grouping + ']. Check the length of column ([Column_varchar]) AGAIN and see whether 10,000 characters are inserted or not. I only presented the INSERT INTOEXEC() AT technique because you seemed open to parking a VIEW on the remote instanceimplying you would always know the table structure , Viewing 15 posts - 1 through 15 (of 15 total), You must be logged in to reply to this topic. So basically, if you have 2008, both the text solution and the varchar(max) will work, so you will have time to change it =-). Thanks for contributing an answer to Database Administrators Stack Exchange! By clicking Accept all cookies, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy. The query stored in the variable receives truncated once it reaches the limit. The Miserly SQL Server By clicking Post Your Answer, you agree to our terms of service, privacy policy and cookie policy. You still Cannot have a Single Unbroken Literal String Larger than 8000 (or 4000 for nVarChar). How much more? You can also deploy your python app after containerizing the application using Docker & Azure container registry, but that's a lesson for another day. No we are not using BEGIN TRANSACTION / COMMIT TRANSACTION. - the incident has nothing to do with me; can I use this this way? where the SQL statement is built on the fly whether you are using ASP.NET, ColdFusion, , @ccId = @clientId, @StartDate_str = @startdate, @EndDate_str = @enddate; Print 'THE START DATE ENTERED BY THE USER WHILE SEARCHING WITH DATE RANGE, IS EITHER NULL OR EMPTY , PLEASE CONTACT SYSTEM ADMINISTRATOR!!! [All], ' + @ArticleFilter + '), AS ([Measures]. if the @sqlquery has more than 8000 character, how to overcome it? In most cases, the character string can contain dummy host variables. ou are not passing parameters via sp+executesql, so you'd be good to go, i think. You can create more general purpose, flexible applications by using dynamic SQL because the full text of a SQL statement may be unknown at compilation. Even the while loop condition on shop parameter does not help us because we have to get Top N value for all the shops and in case of while loop it gives the Top N value of each shop. I mean to say, the query which you given for 8000+ width gives error on Both version of 2005/2008. vegan) just to try it, does this inconvenience the caterers and staff? Asking for help, clarification, or responding to other answers. rev2023.3.3.43278. Dynamic SQL is the SQL statement that is constructed and executed at runtime based on input parameters passed. Why is this sentence from The Great Gatsby grammatical? false, totally 110% false. Thanks for contributing an answer to Stack Overflow! Un ejemplo de la formula es : a.arpAncho-(2*L.apzCalibre)-1, donde cadacampo , Ancho y Calibre son Medidas de una Pieza de madera rectangular, es una medida que se encuentra en una tabla. [Store Transaction Motive].&[U+]. Executes a Transact-SQL statement or batch that can be reused many times, or one that has been built dynamically. Also, I agree the first example isn't truly dynamic SQL, but it shows how to create a query that can be changed using parameters versus hardcoding items. [' + @Grouping + '].CURRENTMEMBER.MEMBER_CAPTION. Warning: debug a script that generated a very long dynamic SQL section. 2. [Shop Model].&[Retail], [Shop]. and see a solution for it. not working even like this exec(@str1+@str2+@str3). [Stores2 Sales Value Net inc VAT - Base],[Measures]. Variable-length Unicode character data. How Intuit democratizes AI development across teams through reusability. [Measures].[CountryDelivered],[Measures].[SQM],[Measures]. [Fiscal Hierarchy].[All],[TransactionType]. - RelativitySQL Jan 30, 2021 at 21:25 Show 1 more comment 7 DECLARE @sql VARCHAR (max) SET @sql = 'SELECT * FROM myTable' Exec @sql Note: Print (@sql) to be built correctly and therefore run. Browse other questions tagged, Where developers & technologists share private knowledge with coworkers, Reach developers & technologists worldwide. SQL Server Usage. [Shop by Model].[Brand].&[7FAM].&[Retail].&[0D8],[Shop]. varchar(max) also should work just fine - could you please try something like the following? [Stores2 Sales Quantity], MEMBER [Measures]. It can't be used to create dynamic procedures (any CREATE PROCEDURE would have a static definition based on the :SETVAR values in effect originally), but it can be used for some very powerful dynamic scripts.These variables can be used anywhere, in strings, as server, table, or database name, or even parts of names.The variable definition is active for the entire script, even across GO. nvarchar(max), when it is a column, will hold 2GB in each row. It is a little confusing that I used the same name twice. [Shop by Model].[Brand].&[7FAM].&[Outlet].&[0D1],[Shop]. Did you try? I wished to use TEXT data type to store this query, but MSDN shows a warning message that Microsoft is planning to remove Text, NText and Image data types from their next versions. Dynamic SQL is a programming technique that enables you to build SQL statements dynamically at runtime. Another obscure option that will work but is not advisable is to store the variable in a text file by using command shell commands to read/write the file. Then you could just call the sproc or the view instead of using such a long statement. Native Dynamic SQL is the easier way to write dynamic SQL. But even if you use VARCHAR (MAX), you should be careful while working on more than 8000 characters. stored procedure? Thanks a lot Sergiy. Workload management Database objects Loads Queries Metadata DMV's will reset when a dedicated SQL pool is paused or when it is scaled. Linear regulator thermal information missing in datasheet. Please assist me with this problem i seemed not knowing way forward! Making statements based on opinion; back them up with references or personal experience. I thought of storing this query in a separate file, but as it uses joins on table variables and other procedure-specific parameters, I doubt if this is possible. @SQL = 'INSERT INTO Work_Flow.dbo.Customer_Calendar (leavetype, leavereason) SELECT *. set @ParmDefinition = N'@StartDate_str DATE'; EXEC sp_executesql @SQLString, @ParmDefinition, @StartDate_str = @startdate; -- narrow down the report based on the requester or authoriser, or both, if((@requster is not null) and (@authoriser is null)), Select [Account Number], [Shareholder Name], , [Current Holdings], [Affected Register], from #finalrecord Where Requester like '%'[emailprotected]+'%', order by [Change Date] asc, holder_id asc, else if ((@authoriser is not null) and (@authoriser is null)), from #finalrecord Where Authoriser like '%'[emailprotected]+'%', else if ((@requster is not null) and (@authoriser is not null)), from #finalrecord Where Requester like '%'[emailprotected]+'%' and Authoriser like '%'[emailprotected]+'%', from #finalrecord order by [Change Date] asc, holder_id asc, IF(@changeType not in ('edmms', 'change of name', 'change of address', 'correction of name', 'correction of CHN')). solution simple and efficient You did not mention using :SETVAR in scripts running in SQLCMD mode. You can probably avoid truncation by defining all the variables involved as nvarchar(MAX). ALTER FUNCTION [dbo]. Este bloque se encuentra en el procedimiento 2 el cual es invocado por el procedimiento 1.