How to execute the sql function - sql

How can I execute this function?
I tried as Select [dbo].[GetPaidInfo]("1"), but I get the error:
An insufficient number of arguments were supplied for the procedure or
function dbo.GetPaidInfo.
USE [PCJ_BM]
GO
/****** Object: UserDefinedFunction [dbo].[GetPaidInfo] Script Date: 3/24/2018 5:05:15 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[GetPaidInfo] (
#InvId INT
,#PmtType VARCHAR(10)
)
RETURNS NVARCHAR(200)
AS
BEGIN
-- Declare the return variable here
DECLARE #PaidInfo NVARCHAR(200)
DECLARE #payment2 VARCHAR(50) = ''
DECLARE #payment3 VARCHAR(50) = ''
DECLARE #card VARCHAR(50) = (
SELECT Card
FROM Payment
WHERE (InvId = #InvId)
)
DECLARE #Currency2 VARCHAR(50) = (
SELECT Currency2
FROM Payment
WHERE (InvId = #InvId)
)
DECLARE #Amt2 VARCHAR(50) = (
SELECT Amt2
FROM Payment
WHERE (InvId = #InvId)
)
DECLARE #Currency3 VARCHAR(50) = (
SELECT Currency3
FROM Payment
WHERE (InvId = #InvId)
)
DECLARE #Amt3 VARCHAR(50) = (
SELECT Amt3
FROM Payment
WHERE (InvId = #InvId)
)
IF (#PmtType = 'Cash')
BEGIN
IF (#Currency2 != NULL OR #Currency2 != '')
BEGIN
SET #payment2 = ' + ' + #Currency2 + ' ' + #Amt2
END
IF (#Currency3 != NULL OR #Currency3 != '')
BEGIN
SET #payment3 = ' + ' + #Currency3 + ' ' + #Amt3
END
SET #PaidInfo = (
SELECT 'Paid in Cash by ' + Currency1 + ' ' + CONVERT(VARCHAR, Amt1) + #payment2 + #payment3
FROM Payment
WHERE (InvId = #InvId)
)
END
ELSE
BEGIN
SET #PaidInfo = (
SELECT 'Paid in Card by ' + CONVERT(VARCHAR, Amt1) --, Currency2, Amt2, Currency3, Amt3
FROM Payment
WHERE (InvId = #InvId)
)
END
-- Return the result of the function
RETURN #PaidInfo
END
My table looks like:

Call your function like this (INT no quotes, VARCHAR(10) single quotes):
SELECT [dbo].[GetPaidInfo] (1,'Cash');
Be aware your function returns NVARCHAR(200).
It appears you are planning to concatenate some information there, so if you start to see some of your string truncated, you might want to increase the length.

As per function definition, it requires 2 params : #InvId & #PmtType.
You should pass both of them during function call like follows:-
SELECT dbo.GetPaidInfo(2, 'Card');

Related

Error in using SELECT to set a variable value in SQL

I have following stored procedure and I have identified the issue with the stored procedure is that using select to set the value of #DeliveryAddress variable and so for all the Letter Requests raised it is only retaining the last value which is in Requests. I tried using SET by explicitly setting each value used in #DeliveryAddresss Calculation but of no use as I ended of getting error that subquery returns multiple rows.
I am unable to understand what shall I change in this SP, so that for each value in #Requests, a different #deliveryAddress value is set and used for insertion in LetterRequest table. Please help.
Note #WorkFlowAcct is a temp table having around 10 unique AccountIds and for each account we have atleast one debtorid.
ALTER PROCEDURE [dbo].[WorkFlow_Action_RequestLetterPref]
AS
DECLARE #LetterID INTEGER;
DECLARE #LetterType CHAR(3);
DECLARE #LetterDescription VARCHAR(50);
DECLARE #JobName VARCHAR(256);
DECLARE #DateCreated DATETIME;
DECLARE #DeliveryMethod VARCHAR(7);
DECLARE #DeliveryAddress VARCHAR(1023);
SELECT #LetterID = [LetterID],
#LetterType = CASE
WHEN [type] IN ('SIF', 'PIF', 'PPS', 'PDC', 'ATT', 'CUS') THEN [type]
ELSE 'DUN'
END,
#LetterDescription = ISNULL([Description], ''),
FROM [dbo].[letter]
WHERE [code] = #LetterCode;
DECLARE #Requests TABLE (
[AccountID] INTEGER NOT NULL,
[DebtorID] INTEGER NOT NULL,
[Seq] INTEGER NOT NULL,
[ErrorMessage] VARCHAR(500) NULL
);
IF #PrimaryDebtor = 1 OR #LetterType IN ('CUS', 'ATT') BEGIN
INSERT INTO #Requests ([AccountID], [DebtorID], [Seq])
SELECT DISTINCT [master].[number] AS [AccountID],
[Debtors].[DebtorID] AS [DebtorID],
[Debtors].[Seq] AS [Seq],
FROM #WorkFlowAcct AS [WorkFlowAcct]
INNER JOIN [dbo].[master] WITH (NOLOCK)
ON [WorkFlowAcct].[AccountID] = [master].[number]
INNER JOIN [dbo].[customer] WITH (NOLOCK)
ON [master].[customer] = [customer].[customer]
INNER JOIN [dbo].[Debtors] WITH (NOLOCK)
ON [master].[number] = [Debtors].[number]
AND [Debtors].[Seq] = [master].[PSeq]
LEFT OUTER JOIN [dbo].[DebtorAttorneys]
ON [Debtors].[DebtorID] = [DebtorAttorneys].[DebtorID];
END;
DECLARE #Street1 VARCHAR(512);
DECLARE #Street2 VARCHAR(512);
DECLARE #City VARCHAR(512);
DECLARE #Country VARCHAR(512);
DECLARE #Zip VARCHAR(512);
IF #Pref = 'Letter'
BEGIN
SET #DeliveryMethod = 'Letter';
SELECT #DeliveryAddress = [Street1] + ' ' + [Street2] + ' ' + [City] + ' ' + [Zipcode] + ' ' + [Country], #Street1 = [Street1], #Street2 = [Street2], #City = [City], #Country = [Country], #Zip = [ZipCode] FROM [Debtors] inner join #Requests AS Requests on [Debtors].[DebtorID] = Requests.[DebtorID] AND [Street1] IS NOT NULL;
IF #Street2 IS NULL
BEGIN
SET #DeliveryAddress = #Street1 + ' ' + #City + ' ' + #Zip + ' ' + #Country;
END
END
SET #DateCreated = GETDATE();
SET #JobName = 'WorkFlow_' + CAST(NEWID() AS CHAR(36)) + CAST(NEWID() AS CHAR(36)) + CAST(NEWID() AS CHAR(36)) + CONVERT(VARCHAR(50), GETDATE(), 126);
BEGIN TRANSACTION;
--Updated params for current Letter Request Table
INSERT INTO [dbo].[LetterRequest] ([AccountID], [LetterID], [LetterCode], [DeliveryMethod], [DeliveryAddress])
SELECT [Requests].[AccountID],
[Requests].[CustomerCode],
#LetterID AS [LetterID],
#LetterCode AS [LetterCode],
#DeliveryMethod AS [DeliveryMethod],
#DeliveryAddress AS [DeliveryAddress]
FROM #Requests AS [Requests]
INNER JOIN #AllowedCustomers AS [AllowedCustomers]
ON [Requests].[CustomerCode] = [AllowedCustomers].[CustomerCode]
WHERE [Requests].[ErrorMessage] IS NULL;
COMMIT TRANSACTION;
RETURN 0;

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

MSSQL - Create table function, return substring

I need to create this table function. The function needs to return single words from passed parameters like: hello, hhuu, value
The table function should return:
hello,
hhuu,
value
But I am always getting some errors, please could you help me?
you can write as:
DECLARE #input_char VARCHAR(255)
SET #input_char = 'hello, hhuu, value'
;WITH cte AS (
SELECT
CAST('<r>' + REPLACE(#input_char, ' ', '</r><r>') + '</r>' AS XML) AS input_char
)
SELECT
rtrim( LTRIM (xTable.xColumn.value('.', 'VARCHAR(MAX)')) ) AS input_char
FROM cte
CROSS APPLY input_char.nodes('//r') AS xTable(xColumn)
Please give a look at this article:
http://www.codeproject.com/Tips/625872/Convert-a-CSV-delimited-string-to-table-column-in
and you could use ' ' (space) as delimiter.
SELECT * FROM dbo.CSVtoTable('hello, hhuu, value', ' ')
I have used the following function many times. It is a bit lengthy forgive me, but it has become a great tool for me.
CREATE Function [dbo].[ParseText2Table]
(
#p_SourceText varchar(MAX)
,#p_Delimeter varchar(100) = ',' --default to comma delimited.
)
RETURNS #retTable TABLE
(
POSITION INT
,Int_Value bigint
,Num_value REAL--Numeric(18,3)
,txt_value varchar(MAX)
)
AS
BEGIN
DECLARE #tmpTable TABLE
(
Position2 INT IDENTITY(1,1) PRIMARY KEY
,Int_Value bigint
,Num_value REAL--Numeric(18,3)
,txt_value varchar(MAX)
)
DECLARE #w_Continue INT
,#w_StartPos INT
,#w_Length INT
,#w_Delimeter_pos INT
,#w_tmp_int bigint
,#w_tmp_num REAL--numeric(18,3)
,#w_tmp_txt varchar(MAX)
,#w_Delimeter_Len INT
IF len(#p_SourceText) = 0
BEGIN
SET #w_Continue = 0 -- force early exit
END
ELSE
BEGIN
-- if delimiter is ' ' change
IF #p_Delimeter = ' '
BEGIN
SET #p_SourceText = replace(#p_SourceText,' ','ÿ')
SET #p_Delimeter = 'ÿ'
END
-- parse the original #p_SourceText array into a temp table
SET #w_Continue = 1
SET #w_StartPos = 1
SET #p_SourceText = RTRIM( LTRIM( #p_SourceText))
SET #w_Length = DATALENGTH( RTRIM( LTRIM( #p_SourceText)))
SET #w_Delimeter_Len = len(#p_Delimeter)
END
WHILE #w_Continue = 1
BEGIN
SET #w_Delimeter_pos = CHARINDEX( #p_Delimeter
,(SUBSTRING( #p_SourceText, #w_StartPos
,((#w_Length - #w_StartPos) + #w_Delimeter_Len)))
)
IF #w_Delimeter_pos > 0 -- delimeter(s) found, get the value
BEGIN
SET #w_tmp_txt = LTRIM(RTRIM( SUBSTRING( #p_SourceText, #w_StartPos
,(#w_Delimeter_pos - 1)) ))
IF dbo.isReallyNumeric(#w_tmp_txt) = 1 --and not #w_tmp_txt in('.', '-', '+', '^')
BEGIN
--set #w_tmp_int = cast( cast(#w_tmp_txt as real) as bigint)--numeric) as bigint)
SET #w_tmp_int = CASE WHEN (CAST(#w_tmp_txt AS REAL) BETWEEN -9223372036854775808 AND 9223372036854775808) THEN CAST( CAST(#w_tmp_txt AS REAL) AS bigint) ELSE NULL END
SET #w_tmp_num = CAST( #w_tmp_txt AS REAL)--numeric(18,3))
END
ELSE
BEGIN
SET #w_tmp_int = NULL
SET #w_tmp_num = NULL
END
SET #w_StartPos = #w_Delimeter_pos + #w_StartPos + (#w_Delimeter_Len- 1)
END
ELSE -- No more delimeters, get last value
BEGIN
SET #w_tmp_txt = LTRIM(RTRIM( SUBSTRING( #p_SourceText, #w_StartPos
,((#w_Length - #w_StartPos) + #w_Delimeter_Len)) ))
IF dbo.isReallyNumeric(#w_tmp_txt) = 1 --and not #w_tmp_txt in('.', '-', '+', '^')
BEGIN
--set #w_tmp_int = cast( cast(#w_tmp_txt as real) as bigint)--as numeric) as bigint)
SET #w_tmp_int = CASE WHEN (CAST(#w_tmp_txt AS REAL) BETWEEN -9223372036854775808 AND 9223372036854775808) THEN CAST( CAST(#w_tmp_txt AS REAL) AS bigint) ELSE NULL end
SET #w_tmp_num = CAST( #w_tmp_txt AS REAL)--numeric(18,3))
END
ELSE
BEGIN
SET #w_tmp_int = NULL
SET #w_tmp_num = NULL
END
SELECT #w_Continue = 0
END
INSERT INTO #tmpTable VALUES( #w_tmp_int, #w_tmp_num, #w_tmp_txt )
END
INSERT INTO #retTable SELECT Position2, Int_Value ,Num_value ,txt_value FROM #tmpTable
RETURN
END
Here are the supporting functions for above as well:
CREATE FUNCTION dbo.isReallyInteger
(
#num VARCHAR(64)
)
RETURNS BIT
BEGIN
IF LEFT(#num, 1) = '-'
SET #num = SUBSTRING(#num, 2, LEN(#num))
RETURN CASE
WHEN PATINDEX('%[^0-9-]%', #num) = 0
AND CHARINDEX('-', #num) <= 1
AND #num NOT IN ('.', '-', '+', '^')
AND LEN(#num)>0
AND #num NOT LIKE '%-%'
THEN
1
ELSE
0
END
END
CREATE FUNCTION dbo.isReallyNumeric
(
#num VARCHAR(64)
)
RETURNS BIT
BEGIN
IF LEFT(#num, 1) = '-'
SET #num = SUBSTRING(#num, 2, LEN(#num))
DECLARE #pos TINYINT
SET #pos = 1 + LEN(#num) - CHARINDEX('.', REVERSE(#num))
RETURN CASE
WHEN PATINDEX('%[^0-9.-]%', #num) = 0
AND #num NOT IN ('.', '-', '+', '^')
AND LEN(#num)>0
AND #num NOT LIKE '%-%'
AND
(
((#pos = LEN(#num)+1)
OR #pos = CHARINDEX('.', #num))
)
THEN
1
ELSE
0
END
END
Usage Examples:
--Single Character Delimiter
--select * from dbo.ParseText2Table('100|120|130.56|Yes|Cobalt|Blue','|')
--select txt_value from dbo.ParseText2Table('100 120 130.56 Yes Cobalt Blue',' ') where Position = 3
--select * from dbo.ParseText2Table('100,120,130.56,Yes,Cobalt,Blue,,',',')
/*
POSITION Int_Value Num_value txt_value
----------- ----------- -------------------- --------------
1 100 100.000 100
2 120 120.000 120
3 131 130.560 130.56
4 NULL NULL Yes
5 NULL NULL Cobalt Blue
*/

Passing parametrs to dynamic query

I have a stored procedure as following, I need to pass paramters to the dynamic pivot. My query runs, I just need to do some filtering based on the passed parameters
-- AND (#SelectedSystemIDs IS NULL OR System.ID IN(select * from dbo.SplitInts_RBAR_1(#SelectedSystemIDs, ',')))
--AND ((#PlatformID IS NULL) OR (System.PlatformID = #PlatformID) OR (#PlatformID = 12 AND System.PlatformID <= 2))
-- AND (ServiceEntry.ServiceDateTime between #StartDate and #EndDate)
so I want to add the above criteria, how could achieve that?
ALTER PROCEDURE [dbo].[spExportStuff]
(#StartDate datetime,
#EndDate datetime,
#SelectedSystemIDs nvarchar (2000) = NULL,
#SelectedTsbIDs nvarchar (2000) = NULL,
#UserRoleID int
)
AS
DECLARE #InstrumentType int = NULL
DECLARE #PlatformID int = null
IF (#SelectedSystemIDs = '')
begin
SET #SelectedSystemIDs = NULL
END
IF (#SelectedTsbIDs = '')
begin
SET #SelectedTsbIDs = NULL
END
IF(#UserRoleID = 1)
BEGIN
SET #PlatformID = 1
END
IF(#UserRoleID = 2)
BEGIN
SET #PlatformID = 2
END
IF (#UserRoleID = 3)
BEGIN
SET #PlatformID = 12
END
IF(#UserRoleID = 4)
BEGIN
SET #PlatformID = 3
END
IF(#UserRoleID = 5)
BEGIN
SET #PlatformID = 4
END
IF(#UserRoleID = 6)
BEGIN
SET #PlatformID = NULL
END
DECLARE #PivotColumnHeaders NVARCHAR(MAX)
SELECT #PivotColumnHeaders =
COALESCE(
#PivotColumnHeaders + ',[' + cast(SystemFullName as Nvarchar) + ']',
'[' + cast(SystemFullName as varchar)+ ']'
)
FROM System
DECLARE #PivotTableSQL NVARCHAR(MAX)
SET #PivotTableSQL = N'
SELECT *
FROM (
SELECT
TSBNumber [TSBNumber],
SystemFullName,
ClosedDate
FROM ServiceEntry
INNER JOIN System
ON ServiceEntry.SystemID = System.ID
Group By TSBNumber, SystemFullName, ClosedDate
) AS PivotData
PIVOT (
max(ClosedDate)
FOR SystemFullName IN (
' + #PivotColumnHeaders + '
)
) AS PivotTable
'
EXECUTE(#PivotTableSQL)
you can construct the required criteria as another input to the stored procedure and append it to the dynamic query
ALTER PROCEDURE [dbo].[spExportStuff]
(#StartDate datetime,
#EndDate datetime,
#SelectedSystemIDs nvarchar (2000) = NULL,
#SelectedTsbIDs nvarchar (2000) = NULL,
#UserRoleID int,
#WhereClause varchar(max) -> this is the new parameter.
)
DECLARE #PivotTableSQL NVARCHAR(MAX)
SET #PivotTableSQL = N'
SELECT *
FROM (
SELECT
TSBNumber [TSBNumber],
SystemFullName,
ClosedDate
FROM ServiceEntry
INNER JOIN System
ON ServiceEntry.SystemID = System.ID
Group By TSBNumber, SystemFullName, ClosedDate
) AS PivotData
PIVOT (
max(ClosedDate)
FOR SystemFullName IN (
' + #PivotColumnHeaders + '
)
) AS PivotTable
' + #WhereClause -> you can append the where clause here.
EXECUTE(#PivotTableSQL)

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