我想基于数组中的值多次运行查询。 我离我很近,但是我不知道如何通过迭代调用查询。我在网上找到的示例显示“执行过程”,但随后没有显示过程的内容,因此我不知道如何让查询以正确的方式引用过程。
在下面的代码中,我首先显示了迭代过程,然后有一个名为QueryIWantToUse
的过程。
INSERT INTO @ids (id)
SELECT 'CTMContactOrigin' UNION
SELECT 'PMMParameters' UNION
SELECT 'TAXTABLE'
DECLARE @i INT
DECLARE @cnt INT
SELECT @i = MIN(idx) - 1, @cnt = MAX(idx) FROM @ids
WHILE @i < @cnt
BEGIN
SELECT @i = @i + 1
DECLARE @id = SELECT id FROM @ids WHERE idx = @i
EXEC QueryIWantToUse @id
END
--QueryIWantToUse:
DECLARE @Table nvarchar(max),
@EntityName nvarchar(max),
@EntityLeaf nvarchar(max),
@EntityCode nvarchar(10),
@CodeRefTable_EN nvarchar(max),
@CodeRefTable_MS nvarchar(max),
@sql nvarchar(max);
SET @Table = @id -- Here I want the array values to be used somehow
SET @EntityName =
(SELECT ENTITYTABLE FROM [Tobias_AX_MasterZWS_test].[dbo].[DMFENTITY] --MASTER DB NAAM
WHERE [Tobias_AX_MasterZWS_test].[dbo].[DMFENTITY].ENTITYTYPENAME = @Table
)
SET @EntityLeaf = @EntityName + '_Leaf'
SET @EntityCode =
(SELECT Code FROM [MDS_AX2012_ZWS].[mdm].[tbl_1_2_EN]
WHERE [MDS_AX2012_ZWS].[mdm].[tbl_1_2_EN].[NAME] = @EntityName
)
SET @CodeRefTable_EN = 'tbl_'+@EntityCode +'_EN'
SET @CodeRefTable_MS = 'tbl_'+@EntityCode +'_MS'
DECLARE @TableName_EN sysname = @CodeRefTable_EN,
@TableName_MS sysname = @CodeRefTable_MS;
SET @sql = N'SELECT * FROM [MDS_AX2012_ZWS].[dbo].[AxVersionTable] WHERE [MDS_AX2012_ZWS].[dbo].[AxVersionTable].EntityName ' + --change to DELETE FROM after testing
N' = ' +
quotename(@EntityName, '''') +
N';';
EXEC sp_executesql @sql;
SET @sql = N'SELECT * FROM [MDS_AX2012_ZWS].[STG].' + quotename(@EntityLeaf) --change to DROP TABLE after testing
EXEC sp_executesql @sql;
SET @sql = N'SELECT * FROM [MDS_AX2012_ZWS].[MDM].' + quotename(@TableName_EN) + 'WHERE VERSION_ID <> 1337'; --change to DELETE FROM after testing
EXEC sp_executesql @sql;
SET @sql = N'SELECT * FROM [MDS_AX2012_ZWS].[MDM].' + quotename(@TableName_MS) + 'WHERE VERSION_ID <> 1337'; --change to DELETE FROM after testing
EXEC sp_executesql @sql;
SET @sql = N'SELECT * FROM [MDS_AX2012_ZWS].[MDM].' + quotename(@TableName_EN); --change to DROP TABLE after testing
EXEC sp_executesql @sql;
SET @sql = N'SELECT * FROM [MDS_AX2012_ZWS].[MDM].' + quotename(@TableName_MS); --change to DROP TABLE after testing
EXEC sp_executesql @sql;
SET @sql = N'SELECT * FROM [Tobias_AX_MasterZWS_test].[dbo].' + quotename(@EntityName); --change to TRUNCATE TABLE after testing
EXEC sp_executesql @sql;
SET @sql = N'SELECT * FROM [Tobias_AX_MasterZWS_test].[dbo].[DMFENTITY] WHERE [Tobias_AX_MasterZWS_test].[dbo].[DMFENTITY].EntityTable ' + --change to DELETE FROM after testing
N' = ' +
quotename(@EntityName, '''') +
N';';
EXEC sp_executesql @sql;
有人建议如何将迭代与过程联系起来吗?