What's the limit of a variable in T-SQL? Why does my variable prints out as NULL? - sql

I'm creating a stored procedure with the following code:
CREATE OR ALTER PROCEDURE Insert_Into_Table
#Origin VARCHAR(255),
#Destination VARCHAR(255),
#Origin_Columns VARCHAR (4000),
#Destination_Columns VARCHAR (4000),
#Delete_Date_Column_Name VARCHAR(63), --Nullable
#Delete_Period_Months INT -- Nullable
AS
BEGIN TRY
DECLARE #insert_query VARCHAR(4000) = NULL;
DECLARE #delete_query VARCHAR(4000) = NULL;
DECLARE #check_query VARCHAR (4000) = NULL;
DECLARE #Date_To_Delete DATETIME = CAST(DATEADD(MONTH, -#Delete_Period_Months, GETDATE()) AS DATETIME);
-- Table names cannot be referenced directly in SPs, so we bypass
-- this issue by declaring a variable containing the query
IF #Delete_Date_Column_Name IS NOT NULL
OR #Delete_Period_Months IS NOT NULL
SET #delete_query = 'DELETE FROM ' + #Destination + ' WHERE ' +
#Delete_Date_Column_Name + ' >= ' + CONCAT(CHAR(39),CAST(#Date_To_Delete AS VARCHAR(255)),CHAR(39));
ELSE
PRINT N'Missing or no values provided for table deletion. Only executing copy';
CREATE TABLE #temptable (count INT)
SET #check_query = 'INSERT INTO #temptable SELECT TOP 1 1 AS count FROM ' + #Origin
EXECUTE(#check_query)
SET #insert_query = 'INSERT INTO' + QUOTENAME(#Destination) + QUOTENAME(#Destination_Columns, '()') +
'SELECT ' + #Origin_Columns + ' FROM ' + QUOTENAME(#Origin);
BEGIN TRY
IF EXISTS (SELECT TOP 1 * FROM #temptable)
BEGIN TRANSACTION
EXECUTE(#delete_query);
EXECUTE(#insert_query);
COMMIT
END TRY
BEGIN CATCH
ROLLBACK;
THROW 51000, 'The Origin table is empty', 1;
END CATCH
END TRY
BEGIN CATCH
THROW 51000, 'Error creating transaction', 1;
END CATCH
GO
When executing the stored proecedure with the parameters shown, it works correctly:
EXEC Insert_Into_Table
#Origin = 'Sink_Proc',
#Destination = 'Sink_Test',
#Origin_Columns = 'customer, order_number, created_date',
#Destination_Columns = 'customer, order_number, created_date',
#Delete_Date_Column_Name = NULL,
#Delete_Period_Months = NULL
However, when executing it with 25+ columns as Origin/Destination columns, when I print the #insert_query variable, it returns NULL and no operation is done. Why is this happening?

Related

How to create a Stored Procedure in SQL Server?

I was creating a Stored Procedure for validation based on not allowing special characters in LeaveTypeText, for my project that I am learning now. And I want LeaveTypeText to not allow duplicate values and update LeaveTypeKey based on LeaveTypeText by removing space in between two characters.
How can I correct this?
ALTER PROCEDURE [dbo].[PreSaveAnd_AfterSave_Validation] (
#FBFormId INT
,#PkId INT
,#TF_ProjectId INT
,#UserDetails NVARCHAR(MAX)
,#IsPostSave BIT
,#ContactId INT
,#Who NVARCHAR(100)
,#RoleId INT
,#Culture NVARCHAR(200)
)
AS
BEGIN
DECLARE #GlobalDateFormatCode INT
DECLARE #ErrorMsg NVARCHAR(Max)
SELECT #GlobalDateFormatCode = dbo.TF_FN_GetCurrentDateFormat()
IF ISNULL(#IsPostSave, 0) = 0
BEGIN
DECLARE #ParaMeterTable TABLE (
Id INT IDENTITY(1, 1) PRIMARY KEY
,ParameterName NVARCHAR(MAX)
,ParameterValue NVARCHAR(MAX)
)
INSERT INTO #ParaMeterTable (
ParameterName
,ParameterValue
)
SELECT LTRIM(LEFT(Value, CHARINDEX('=', Value, 0) - 1)) AS ParameterName
,LTRIM(SUBSTRING(Value, CHARINDEX('=', Value, 0) + 1, LEN(Value))) AS ParameterValue
FROM dbo.TF_FN_Split(#UserDetails, '||')
WHERE ISNULl(Value, '') <> ''
--SELECT * FROM #ParaMeterTable
DECLARE #LeaveTypeText NVARCHAR(1000)
DECLARE #LeaveTypeKey NVARCHAR(1000)
--SELECT #LeaveTypeText = ParameterValue
--FROM #ParaMeterTable
--WHERE ParameterName LIKE '#LeaveTypeText%'
--select #LeaveTypeKey = LeaveTypeKey from DBO.Master_LeaveType_Sample
--SELECT #LeaveTypeText
SET #ErrorMsg = ' "Leave Type Key" field does not allow Special characters '
--Validate Here
IF EXISTS (#LeaveTypeKey like '%$%')
BEGIN
SELECT 0 AS IsValid
,#ErrorMsg AS [ErrorMessage]
END
IF (ISNULL(#ErrorMsg, '') != '')
BEGIN
SELECT 0 AS IsValid
,#ErrorMsg AS [ErrorMessage]
END
ELSE
BEGIN
SELECT 1 IsValid
,dbo.TF_FN_GetCultureMessage('TF_DB_Success', #ContactId, #Who, #RoleId, #Culture) AS [ErrorMessage]
END
END
ELSE IF ISNULL(#IsPostSave, 0) = 1
BEGIN
-- Post Save Logic
UPDATE DBO.Master_LeaveType_Sample
SET LeaveTypeKey = Replace(ParameterValue, ' ', '')
FROM DBO.Master_LeaveType_Sample
WHERE LeaveTypeText = ParameterValue
SELECT 1 IsValid
,dbo.TF_FN_GetCultureMessage('TF_DB_Success', #ContactId, #Who, #RoleId, #Culture) AS [ErrorMessage]
END
END

How to split and replace with stored procedure?

I want to replace all e_Mail column where in #tablename with my users table (my main table).
For example:
#tablename
[name] [eMail] // columns
------------------------------------------------------
name surname blahblah#gmail.com
My users table
[name] [eMail]
----------------------------------------
name surname blahblah#hotmail.com
I want to update this row's eMail column as 'blahblah#hotmail.com' in #tablename.
What will procedure do?
1- Get first value of eMail column from #tablename
2- Split value (split char: #) and get first value (for example, if value blahblah#gmail.com, get gmail.com)
3- Search first value in users table
4- When the find value in users table, (Code must find blahblah#hotmail.com) Update eMail as blahblah#hotmail.com in #tablename
5- Get second value of eMail column from #tablename
.
.
.
So, I write a stored procedure. But this procedure is not working. Where is the problem?
Create Proc update_eMail
(#tablename nvarchar(50),
#columnname nvarchar(50))
AS
Begin
Declare #get_oldeMail nvarchar(100)
Declare #get_eMail nvarchar(100)
Declare #get_SplitValue nvarchar(100)
Declare #get_oldSplitValue nvarchar(100)
Declare #rowNumber int
Declare #users_rowNumber int
Declare #i int
Declare #j int
Declare #q_getRowNumber NVARCHAR(MAX)
Declare #q_getoldeMail NVARCHAR(MAX)
Declare #q_UpdateQuery NVARCHAR(MAX)
SET #q_getRowNumber = N'SELECT Count(ID)
FROM ' + QUOTENAME(#tablename)
EXECUTE #rowNumber = sp_executesql #q_getRowNumber
/*Set #rowNumber = (Select Count(ID) from #tablename)*/
Set #users_rowNumber = (Select Count(ID) from tblusers)
Set #i = 1
Set #j = 1
While(#i <= #rowNumber)
BEGIN
Set #q_getoldeMail = '(SELECT Lower(#columnname) FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY ID) AS rownumber
,ID
,[Name]
,[Description]
,[Status]
,[AssignedTo]
,[AssignedToMail]
,[CC]
FROM' + #tablename + '
) AS ar
WHERE rownumber = #i)'
EXECUTE #get_oldeMail = sp_executesql #q_getoldeMail
Set #get_oldeMail = REPLACE(#get_oldeMail,'ı','i')
WHILE LEN(#get_oldeMail) > 0
BEGIN
IF CHARINDEX('#',#get_oldeMail) > 0
SET #get_oldSplitValue = SUBSTRING(#get_oldeMail,0,CHARINDEX('#',#get_oldeMail))
ELSE
BEGIN
SET #get_oldSplitValue = #get_oldeMail
SET #get_oldeMail = ''
END
SET #get_oldeMail = REPLACE(#get_oldeMail,#get_oldSplitValue + '#' , '')
END
While(#j <= #users_rowNumber)
BEGIN
Set #get_eMail = (SELECT Replace(Lower(eMail),'ı','i') FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY ID) AS rownumber
,eMail
FROM tblusers) AS ar
WHERE rownumber = #j)
WHILE LEN(#get_eMail) > 0
BEGIN
IF CHARINDEX('#',#get_eMail) > 0
SET #get_SplitValue = SUBSTRING(#get_eMail,0,CHARINDEX('#',#get_eMail))
ELSE
BEGIN
SET #get_SplitValue = #get_eMail
SET #get_eMail = ''
END
SET #get_eMail = REPLACE(#get_eMail,#get_SplitValue + '#' , '')
END
if(#get_splitValue = #get_oldSplitValue)
begin
Set #q_UpdateQuery = 'Update ar Set ' + #columnname + ' = ' + #get_email + ' Where rownumber = ' +#i
EXECUTE sp_executesql #q_UpdateQuery
break
end
SET #j = #j+1
END
SET #i = #i+1
END
End
Thanks in advance.

Procedure to check annual date

I'm trying to create a procedure to verify annual dates. The date is stored one time in the BD, but in the calendar on my winform it shows annually(I use annually bolded dates in C#). So what I want to do with the query, is to check is the month and the day are like the date stored in the table, but does not work. This is my query:
SELECT IdCalendar,
Description,
DateCalendar,
Annualy
FROM Calendar
WHERE
(DATEPART(MONTH,DateCalendar) like DATEPART(MONTH,#DateCalendar)) AND
(DATEPART(DAY,DateCalendar) like DATEPART(DAY,#DateCalendar))
And for example, my stored DateCalendar is '2015-12-04', and I my paramenter #DateCalendar is '2016-12-04'. Any idea about how to do a better query?
EDIT
The query does not have any error or warning. Just returns 0 rows. And my DateCalendar is stored as DateTime.
The SP:
CREATE PROC [dbo].[usp_app_Calendar_Search]
#DateCalendar DATETIME,
#Result SMALLINT OUTPUT,
#Message VARCHAR(1000) OUTPUT
AS
BEGIN
DECLARE #vResult SMALLINT, #vMessage VARCHAR(1000)
SELECT #vResult = 0, #vMessage = ''
BEGIN TRY
IF EXISTS (SELECT * FROM Calendar WHERE DateCalendar = #DateCalendar)
BEGIN
IF(#DateCalendar = 0) SET #DateCalendar = NULL
SELECT IdCalendar,
Description,
DateCalendar,
Annualy
FROM Calendar
WHERE
(DATEPART(MONTH,DateCalendar) like DATEPART(MONTH,#DateCalendar)) AND
(DATEPART(DAY,DateCalendar) like DATEPART(DAY,#DateCalendar))
SET #vResult = 1
SET #vMessage = 'Done'
END
ELSE BEGIN
SET #vResult = 0
SET #vMessage = 'Error.'
END
END TRY
BEGIN CATCH
SET #vResult = -1
SET #vMessage = 'Error: ' + ERROR_MESSAGE() + ' Line: ' + CAST(ERROR_LINE() AS VARCHAR)
END CATCH
SELECT #Result = #vResult, #Message = #vMessage
END
Thanks in advance.
The problem is with IF EXISTS (SELECT * FROM Calendar WHERE DateCalendar = #DateCalendar). I rewrite your SP:
CREATE PROC [dbo].[usp_app_Calendar_Search]
#DateCalendar DATETIME,
#Result SMALLINT OUTPUT,
#Message VARCHAR(1000) OUTPUT
AS
BEGIN
DECLARE #vResult SMALLINT = 0
,#vMessage VARCHAR(1000) = '';
IF(#DateCalendar = 0) SET #DateCalendar = NULL;
BEGIN TRY
SELECT IdCalendar,
Description,
DateCalendar,
Annualy
FROM Calendar
WHERE DATEPART(MONTH,DateCalendar) = DATEPART(MONTH,#DateCalendar)
AND DATEPART(DAY,DateCalendar) = DATEPART(DAY,#DateCalendar);
IF ##ROWCOUNT > 0
SELECT #vResult = 1, #vMessage = 'Done'
ELSE
SELECT #vResult = 0, #vMessage = 'Error.';
END TRY
BEGIN CATCH
SET #vResult = -1
SET #vMessage = 'Error: ' + ERROR_MESSAGE() + ' Line: '
+ CAST(ERROR_LINE() AS VARCHAR)
END CATCH
SELECT #Result = #vResult, #Message = #vMessage;
END
EDIT:
Now the WHERE condition is not-SARGable so it means that query optimizer will skip index on DateCalendar column (if exists any).
You can use computed columns like #Tom Page suggested in comment:
ALTER TABLE Calendar ADD MonthCalendar AS DATEPART(MONTH,DateCalendar);
ALTER TABLE Calendar ADD DayCalendar AS DATEPART(day,DateCalendar);
/*Create Index on Calculated Columns for Month and day*/
CREATE INDEX IX_Calendar_Month_Day ON Calendar(MonthCalendar , DayCalendar);
/*Use Computed Column Index in W*/
DECLARE #DateCalendar datetime = '2015-12-25';
SELECT IdCalendar, Description, DateCalendar, Annualy
FROM Calendar
WHERE MonthCalendar = DATEPART(MONTH,#DateCalendar)
AND DayCalendar = DATEPART(DAY,#DateCalenda);

SQL Server Try Catch

I have a stored procedure that is run by the SQL Agent every x minutes. The stored procedure has a while loop that reads each row and does something with them.
I want to handle errors as they occur in the while loop. I need to use Throw in the CATCH block because then SQL Server Agent will not notify if an error occurred.
But the problem is if I use the throw block it breaks out of the while loop but does not process the other records.
How can I use TRY CATCH in a while loop and if an error occurs it should continue with while loop?
This is my code:
WHILE #i<#Count OR #Count IS NULL
BEGIN
SELECT #Id = NULL --Clear variable
SELECT TOP 1
#Id = Id,
#TableNo = [TableNo],
#Action = [Action],
#RecId = [RecId],
#NDB = dbo.GetDB(CId)
FROM
dbo.alot WITH (NOLOCK)
WHERE
CId = #Cid
AND Error = 0
AND (#Table IS NULL OR TableNo = #Table)
AND Tableno <> 50109
ORDER BY
Id
IF #Id IS NOT NULL
BEGIN
SELECT
#SQL = N'EXECUTE #RC = ['+dbo.GetDB(#CId)+'].[dbo].[alot_web] #TableNo, #Action, #RecId, #NaviDB'
BEGIN TRY
IF #RecId = '0-761345-27353-4'
BEGIN
SELECT 1 / 0; -- Generate an error here.
END
EXEC master.dbo.sp_executesql #SQL, N'#TableNo nvarchar(12), #Action tinyint, #RecId nvarchar(36), #NDB varchar(12), #RC int OUTPUT'
, #TableNo, #Action, #RecId, #NaviDB, #Rc OUTPUT
END TRY
BEGIN CATCH
DECLARE #Description VARCHAR(1024);
SELECT #Description = 'WebQueue ID: ' + ISNULL(CAST(#Id AS VARCHAR), '') + ' CompanyID: ' + ISNULL(#Cid, '') + ' Action: ' + ISNULL(CAST(#Action AS VARCHAR), '') + ' RecID: ' + ISNULL(CAST(#RecId AS VARCHAR), '') + ' #RC: ' + ISNULL(CAST(#RC AS VARCHAR), '');
EXEC dbo.LogError #Description;
THROW;
END CATCH
IF #RC = 0 AND ##ERROR = 0
BEGIN
IF EXISTS(SELECT * FROM Queue
WHERE CId = #CId AND [Action] = #Action
AND TableNo = #Tableno AND RecId = #RecID AND Id <> #Id)
BEGIN
DELETE FROM Queue
WHERE CId = #CId AND [Action] = #Action AND TableNo = #Tableno
AND RecId = #RecID
SELECT #Ok += ##ROWCOUNT
END
ELSE BEGIN
DELETE FROM Queue WHERE Id = #Id
SELECT #Ok += ##ROWCOUNT
END
END
ELSE BEGIN
IF EXISTS(SELECT * FROM Queue
WHERE CId = #CId AND [Action] = #Action
AND TableNo = #Tableno AND RecId = #RecID AND Id <> #Id)
BEGIN
UPDATE Queue
SET Error = 1
WHERE CId = #CId AND [Action] = #Action AND TableNo = #Tableno AND RecId = #RecID
SELECT #Failed += ##ROWCOUNT
END
ELSE BEGIN
UPDATE Queue
SET Error = 1
WHERE Id = #Id
SELECT #Failed += ##ROWCOUNT
END
END
END
ELSE
BREAK
SELECT #i += 1
/*IF #i>0 BEGIN--logging >>
INSERT INTO [AdminDB].[dbo].[Replication_Log] ([Date],[CId],[Loops],[DurationSS],[Ok],[Failed])
SELECT Getdate(),#CId,#i,DATEDIFF(ss,#Startdt,getdate()),#Ok,#Failed
END */
END
Replace your THROW with CONTINUE; this way the next record will be processed without Canceling the code.
(EDITED!)
since you log your errors with
EXEC dbo.LogError #Description;
i think you don't need to rethrow the error. Since you stated you don't want the program to end.
example of CONTINUE:
DECLARE #intFlag INT
SET #intFlag = 1
WHILE (#intFlag <=5)
BEGIN
PRINT #intFlag
SET #intFlag = #intFlag + 1
CONTINUE;
IF #intFlag = 4 -- This will never executed
BREAK;
END
GO
source : http://blog.sqlauthority.com/2007/10/24/sql-server-simple-example-of-while-loop-with-continue-and-break-keywords/
EDIT:
for your job agent:
create a new variable at the top of your procedure :
int #ErrorAmount = 0
your catch would need to look like this:
BEGIN CATCH
DECLARE #Description VARCHAR(1024);
SELECT #Description = 'WebQueue ID: ' + ISNULL(CAST(#Id AS VARCHAR), '') + ' CompanyID: ' + ISNULL(#Cid, '') + ' Action: ' + ISNULL(CAST(#Action AS VARCHAR), '') + ' RecID: ' + ISNULL(CAST(#RecId AS VARCHAR), '') + ' #RC: ' + ISNULL(CAST(#RC AS VARCHAR), '');
EXEC dbo.LogError #Description;
SET #ErrorAmount = #ErrorAmount+1; --add this line
CONTINUE; --REPLACE THROW with CONTINUE
END CATCH
at the end of your procedure Add
if #ErrorAmount > 0
BEGIN
THROW 6000,'Your message' , 1;
END
this way your Agent will show you the error and your whole process still did the job.
Your THROW raises an exception which causes the SP to stop processing. Essentially you are catching any errors that occur but rethrowing them which will indeed break out of the while loop.
Remove it and the sp should then just continue as normal.
My suggestion is use one more loop outside the loop you have.
So the TSQL will be something like this, will this helps?
DECLARE #Continue bit,
#i INT,
#Count INT
SELECT #i = 1 ,
#Count =10
SET #Continue =1
While #Continue=1
BEGIN
BEGIN TRY
--YOUR existing while loop
WHILE #i<#Count OR #Count IS NULL
BEGIN
-- The rest of your code
IF #i=3
BEGIN
set #i= #i/0
END
PRINT #i
SET #i=#i+1
--Set to false when complete
IF #i =#Count
SET #Continue =0
END
END TRY
BEGIN CATCH
print ERROR_MESSAGE()
set #i =#i+1
END CATCH
END
Expected result from above
1
2
Divide by zero error encountered.
4
5
6
7
8
9
Not all errors can be caught by TRY/CATCH. In this case, sp_start_job actually calls external procedures, and these are outside the bounds of SQL Server's error handling. Or at least that's the story that they're sticking to:
http://connect.microsoft.com/SQLServer/feedback/details/362112/sp-start-job-error-handling
Please refer this for more details
You could:
Remove the THROW. Your script will continue as normal and errors will be logged
At the end of the script check #Failed and if appropriate use RAISEERROR which will be noted by the SQL Agent

Update TableType variable in dynamic SQL query

I had created User defined table type in my database. After that I had declared a variable of that table type in my procedure. And I had return my rest of the logic. At the end I am trying to update that table type variable using dynamic SQL.
But I got an error:
Msg 10700, Level 16, State 1, Line 1
The table-valued parameter "#ttbl_TagList" is READONLY and cannot be modified.
How can I solve the error?
User defined table type:
CREATE TYPE [dbo].[tt_TagList] AS TABLE(
[tagListId] [tinyint] IDENTITY(1,1) NOT NULL,
[tagId] [tinyint] NOT NULL DEFAULT ((0)),
[tagName] [varchar](100) NOT NULL DEFAULT (''),
[tagValue] [nvarchar](max) NOT NULL DEFAULT ('')
)
GO
Procedure:
CREATE PROCEDURE [dbo].[P_ReplaceTemplateTag]
AS
BEGIN
SET NOCOUNT ON;
DECLARE #ttbl_TagList dbo.tt_TagList, #V_TagId INT, #V_Counter TINYINT = 1,
#V_FinalQuery NVARCHAR(MAX) = '', #V_TagValue NVARCHAR(MAX);
INSERT INTO #ttbl_TagList (tagId, tagName, tagValue)
SELECT DISTINCT T.tagId, T.tagName, '' AS tagValue
FROM dbo.tbl_Tag T;
WHILE (1 = 1)
BEGIN
SET #V_TagValue = '';
SELECT #V_TagId = tagId FROM #ttbl_TagList WHERE tagListId = #V_Counter;
IF (##ROWCOUNT = 0)
BEGIN
BREAK;
END
IF (#V_TagId = 1)
BEGIN
/* Logic for getting tag value */
SET #V_TagValue = 'Tag Value 1';
END
ELSE IF (#V_TagId = 2)
BEGIN
/* Logic for getting tag value */
SET #V_TagValue = 'Tag Value 2';
END
ELSE IF (#V_TagId = 3)
BEGIN
/* Logic for getting tag value */
SET #V_TagValue = 'Tag Value 3';
END
ELSE IF (#V_TagId = 4)
BEGIN
/* Logic for getting tag value */
SET #V_TagValue = 'Tag Value 4';
END
IF (#V_TagValue != '')
BEGIN
SET #V_FinalQuery = #V_FinalQuery + ' WHEN ' + CONVERT(NVARCHAR(10), #V_Counter) + ' THEN ''' + #V_TagValue + '''';
END
SET #V_Counter = #V_Counter + 1;
END
IF (#V_FinalQuery != '')
BEGIN
SET #V_FinalQuery = N'UPDATE #ttbl_TagList SET tagValue = (CASE tagListId' + #V_FinalQuery + ' END)';
EXECUTE sp_executesql #V_FinalQuery, N'#ttbl_TagList dbo.tt_TagList readonly', #ttbl_TagList;
END
SELECT * FROM #ttbl_TagList;
END
TVP can not be updated directly. So try this one -
CREATE PROCEDURE [dbo].[P_ReplaceTemplateTag]
AS
BEGIN
SET NOCOUNT ON;
IF OBJECT_ID('tempdb.dbo.#t1') IS NOT NULL
DROP TABLE #t1
DECLARE
#ttbl_TagList dbo.tt_TagList
, #V_Counter TINYINT = 1
, #V_FinalQuery NVARCHAR(MAX) = ''
, #V_TagValue NVARCHAR(MAX);
INSERT INTO #ttbl_TagList (tagId, tagName, tagValue)
SELECT DISTINCT tagId, tagName, ''
FROM dbo.tbl_Tag;
WHILE (1 = 1) BEGIN
SELECT #V_TagValue =
CASE
WHEN tagId = 1 THEN 'Tag Value 1'
WHEN tagId = 2 THEN 'Tag Value 2'
WHEN tagId = 3 THEN 'Tag Value 3'
WHEN tagId = 4 THEN 'Tag Value 4'
ELSE ''
END
FROM #ttbl_TagList
WHERE tagListId = #V_Counter;
IF (##ROWCOUNT = 0) BREAK;
IF (#V_TagValue != '')
BEGIN
SET #V_FinalQuery = #V_FinalQuery + ' WHEN ' + CONVERT(NVARCHAR(10), #V_Counter) + ' THEN ''' + #V_TagValue + '''';
END
SET #V_Counter = #V_Counter + 1;
END
IF (#V_FinalQuery != '')
BEGIN
CREATE TABLE #t1
(
tagId TINYINT
, tagName VARCHAR(100)
, tagValue NVARCHAR(MAX)
)
SET #V_FinalQuery = N'
INSERT INTO #t1
SELECT tagId, tagName, (CASE tagListId' + #V_FinalQuery + ' END)
FROM #ttbl_TagList';
EXEC sys.sp_executesql
#V_FinalQuery
, N'#ttbl_TagList dbo.tt_TagList readonly'
, #ttbl_TagList;
END
SELECT * FROM #t1;
END