我有一个很长的查询,可以检索一长串物品,要实现这一点,我需要动态地进行查询:
相关代码:
DECLARE @Sql NVARCHAR(MAX) = '
DECLARE @DList TABLE
(
[ProjectKey] INT
, [DesignKey] INT
...
)
DECLARE @ExistDesignKey BIT = (SELECT TOP 1
1
FROM [#SearchKeys]);
INSERT INTO @DList
SELECT
[p].[ProjectKey]
, [pd].[DesignKey]
...
WHERE ...
';
DECLARE @Select NVARCHAR(MAX) = ' SELECT
*
FROM @DList
ORDER BY
'+@CurrentSortBy+'
, [Design Name]
, [DesignTypeName]
, [DesignNumber]
, [RevisionNumber]
';
DECLARE @Query NVARCHAR(MAX) = @Sql + @Select
因此,如您所见,我创建具有多列的表,然后将数据插入其中。
我要做的是在此表中添加另外两列,但是我需要使用DesignKey列行进行查询。
新列:
DECLARE @CustomerAndContactsTable AS TABLE
(
[CustomerName] VARCHAR(1000)
, [ContactName] VARCHAR(1000)
, [CommunicationType] VARCHAR(255)
, [CommunicationAddress] VARCHAR(1000)
)
INSERT INTO @CustomerAndContactsTable
SELECT
[CU].[Name]
, CONCAT([C].[FirstName] , ' ' , [C].[LastName])
, [CT].[DeviceType]
, [COM].[Address]
FROM [DesignCustomer] AS [DC]
INNER JOIN [Customer] AS [CU] ON [DC].[CustomerKey] = [CU].[CustomerKey]
INNER JOIN [CustomerContact] AS [CC] ON [DC].[CustomerKey] = [CC].[CustomerKey]
INNER JOIN [Contact] AS [C] ON [CC].[ContactKey] = [C].[ContactKey]
INNER JOIN [Communication] AS [COM] ON [c].[ContactGuid] = [com].[ComGuid]
INNER JOIN [ComType] AS [CT] ON [COM].[ComTypeKey] = [CT].[ComTypeKey]
WHERE [DesignKey] = --need designkey of row
AND [c].[IsPrincipal] = 1
AND [COM].[ComTypeKey] IN(1 , 2 , 3 , 4)
AND [DC].[Contracted] = 1
SELECT TOP 1
[CustomerName]
, CONCAT([ContactName] , ' Contact: ' , STUFF(
(SELECT
', '+CONCAT([CommunicationType] , ': ' , [CommunicationAddress])
FROM @CustomerAndContactsTable FOR XML PATH('')
) , 1 , 1 , '')) AS [PrincipalContact]
FROM @CustomerAndContactsTable
GROUP BY
[CustomerName]
, [ContactName]
, [CommunicationType]
, [CommunicationAddress]
我想将这两列设置为CustomerName
和PrincipalContact
,但是如您所见,我需要在@ designkey
表中使用CustomerAndContactsTable
一旦具有DList
值并用于插入另外两列,该如何迭代@@ DesignKey
?