SQL-循环连接数据

时间:2019-05-17 16:42:31

标签: sql sql-server tsql

我有一个宽度/长度未知的数据集,分为不同的表。我正在尝试建立一个为我汇总数据的过程。至此,我可以分别返回每个字段了(请参见下图)。我需要找到一种将DateTime和GroupID上所有返回的表连接在一起的方法,以便获得如下表:

DateTime | GroupID | Name | Age | Balance | ...
-------------------------------------------------------------------
Date1      ID1      data1   data2 data3

我的表格是按照这种方式构造的。

dbo.TagSource:

TagSourceId | Table Name | ...
------------------------------------
01            Table 1
02            Table 2

dbo.Tag:

TagId | TagSourceId | Field Name | RawTableName | ...
------------------------------------------------------
11      01            Name         dbo.StringValue
12      01            Age          dbo.IntegerValue
13      01            Balance      dbo.DecimalValue
14      01            Document     dbo.FileValue
15      02            Name         ExternalTable1
16      02            Height       ExternalTable1
17      02            Occupation   ExternalTable2

dbo。[字符串/整数/小数/文件/ ...]值表:

ValueId | TagId | Value
-------------------------------
101       11      John Smith
102       11      Jane Smith
103       11      John Doe 
104       11      Jane Doe
105       11      Thanos

下面的代码中循环的每次迭代都会给我一个这样的表。

enter image description here

如何为循环的每次迭代在DateTime和GroupID上执行FULL OUTER JOIN? 我尝试将数据存储在临时表中,但是临时表中的列定义是静态的,列的数量,数据类型和名称是动态的。我尝试递归地执行此操作,但是遇到了类似的问题。

USE [DB_Arc];
GO

-- CREATE OR ALTER not support until SQL Server 2016
ALTER PROCEDURE buildFields (@TagSourceId bigint) AS

--DECLARE @TagSourceId bigint = 130;

-- Target Fields - Iterator
DECLARE field_cursor CURSOR STATIC LOCAL FOR
SELECT Id, [Name], RawTableName
FROM dbo.[Tag]
WHERE TagSourceId = @TagSourceID
AND [Name] NOT IN ('DateTime','GroupId')
AND TagTypeId NOT IN (6,7)
ORDER BY Id

OPEN field_cursor

-- Local Variables
DECLARE @TagID bigint, @TagName nvarchar(250), @RawTableName nvarchar(250)
DECLARE @FieldStatement nvarchar(500);
DECLARE @ParamDefinition nvarchar(500);

--Initial field store
FETCH NEXT FROM field_cursor
INTO @TagID, @TagName, @RawTableName

    --Loop through fields and push data to temporary table
    WHILE @@FETCH_STATUS = 0
    BEGIN

        -- Build SQL Statement block
        SET @FieldStatement = 
            N'SELECT
                    CONVERT(datetime2, [DateTime], 1) as DateTime,
                    [GroupId],
                    [Value] AS ' + QuoteName(@TagName) +
            N' FROM ' + QuoteName(@RawTableName) + 
            N' WHERE TagId = @Tag
                AND IsDeleted = 0
                '
              ;
        SET @ParamDefinition = N'@Tag bigint';

        EXECUTE sp_executesql @FieldStatement, @ParamDefinition, @Tag = @TagID;

        --iterate to next field
        FETCH NEXT FROM field_cursor
        INTO @TagID, @TagName, @RawTableName

    END

CLOSE field_cursor
DEALLOCATE field_cursor

;
GO


EXEC buildFields 130; 

0 个答案:

没有答案