首页 > 解决方案 > 如何将 n 个列名分配给单个变量?

问题描述

我有一个包含 SourceFields、TargetFields 和 FileNames 列表的映射表。

SourceField TargetField Filename

A           1           test.xlsx
B           2           test.xlsx
C           3           test.xlsx
d           1           other.xlsx
e           2           other.xlsx

我想根据 TargetField 和 FileName 设置一个 SourceField 变量

        DECLARE
            @FileName NVARCHAR(MAX)                         
            ,@sql1Target NVARCHAR(MAX)
            ,@sql2Target NVARCHAR(MAX)
        -------------------------------------------------------------------------------
            ,@sql1Source NVARCHAR(MAX)                  
            ,@sql2Source NVARCHAR(MAX)
        -------------------------------------------------------------------------------
            ,@sql1Transform NVARCHAR(MAX)               
            ,@sql2Transform NVARCHAR(MAX)

        SET @FileName = 'other.xlsx'                        
        SET @sql1Target = '1'                   
        SET @sql2Target = '2'

        SET @sql1Transform =                            
            'SELECT
                @SourceField = SourceField
            FROM
                MAPPING_DIM
            WHERE
                TargetField = ''1'' and FileName = ' + ''''+ @FileName +''''
        ------------------------------------------------------------------------------------------------------------
        SET @sql2Transform =
                'SELECT
                    @SourceField = SourceField
                FROM
                    MAPPING_DIM
                WHERE
                    TargetField = ''2'' and FileName = ' + ''''+ @FileName +''''

这些语句在执行时将根据其他两个变量返回 SourceField。然后我可以使用这些源变量从我的文件名中进行选择。

        EXECUTE sp_executesql @sql1Transform , N'@SourceField NVARCHAR (MAX) OUTPUT', @SourceField = @sql1Source OUTPUT
        EXECUTE sp_executesql @sql2Transform , N'@SourceField NVARCHAR (MAX) OUTPUT', @SourceField = @sql2Source OUTPUT

我希望能够对包含任意数量列的任何表执行此操作。我目前的问题是,当我的 FileName = 'other.xlsx' 设置了 TargetVariables 时,此代码才会起作用。如果我在 FileName = 'test.xlsx' 的地方这样做,那么我需要将我的变量设置为包含第三个字段。

有什么方法可以根据我的 TargetFields 和 FileName 名称为表中的“n”个列返回我的 SourceFields?

标签: sqlsql-server

解决方案


评论太长了。我认为没有一种简单的方法可以将任意一组值分配给查询结果。

我实际上建议您使用单独的查询设置每个值:

select @a = TargetField
from mapping
where filename = @filename and sourcefield = 'A';

select @b = TargetField
from mapping
where filename = @filename and sourcefield = 'B';

select @c = TargetField
from mapping
where filename = @filename and sourcefield = 'C';

如果没有对应的行,则该值不会改变。但是,您可以使用聚合将值强制为NULL或其他值:

select @a = max(TargetField)
from mapping
where filename = @filename and sourcefield = 'A';

或者:

select @a = coalesce(max(TargetField), '<default value>')
from mapping
where filename = @filename and sourcefield = 'A';

注意:这需要知道可以设置的所有可能值。但是,它不需要动态 SQL。而且,如果您要使用这些值,那么无论如何您都需要知道后续代码中的变量名称。


推荐阅读