通过其名称为第一个表的行名称的另一个表中的selectiong值更新表的列 [英] update a column of a table by selectiong value from another table whose column name is the row name of fist table

查看:58
本文介绍了通过其名称为第一个表的行名称的另一个表中的selectiong值更新表的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表#table列columnname,值



有内容说...

列名值

XYZ NUll
ABC null





另一张桌子我说#datatable有列XYZ,ABC,LMN并且有数据



 XYZ ABC LMN 

1 2 3









我需要先将#table更新为sql查询的结果,



 ColumnName Value 
XYZ 1
ABC 2







请帮助



这是我试过的东西



 DE CLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)

select @cols = STUFF((SELECT','+ QUOTENAME(columnname)
from# table
FOR XML PATH(''),TYPE
).value('。','NVARCHAR(MAX)')
,1,1,'')
打印@cols
设置@query = N'SELECT'+ @cols + N'来自
#datatable
unpivot


for columnname in( '+ @cols + N')
)p'

但错误

消息207,等级16,状态1,行1
无效列名字'XY​​Z'。
消息207,等级16,状态1,行1
无效的列名称'ABC'。

解决方案

您可以取消转动#datatable表,然后进行简单更新,因为您将获得低于值的格式并且在格式化后将格式化为



XYZ 1

ABC 2

LMN 3


  SELECT  COLUMNANME,VALUE 来自 
#datatable
unpivot

value
for COLUMNANME in (XYZ,ABC)
)p


感谢所有人提供帮助以达到unpivot概念


I have one table #table with columns columnname,value

having contents say...

Columnname      value

XYZ              NUll
ABC              null



another table I have say #datatable with Columns XYZ, ABC, LMN and having data

XYZ      ABC         LMN

 1       2           3





I need to update first #table the result of the sql query as,

ColumnName      Value
XYZ             1
ABC             2




Please help

here is what I tried

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)
					 
select @cols = STUFF((SELECT ',' + QUOTENAME(columnname) 
                    from #table
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
print @cols
set @query = N'SELECT ' + @cols + N' from 
             #datatable
               unpivot 
            (
            value    
        for columnname in (' + @cols + N')
            ) p '

but error

Msg 207, Level 16, State 1, Line 1
Invalid column name 'XYZ'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'ABC'.

解决方案

You can Un-Pivot the #datatable table and then make a simple updated as you will have
below values and format after unpivot

XYZ 1
ABC 2
LMN 3


SELECT  COLUMNANME,VALUE  from
             #datatable
               unpivot
            (
            value
        for COLUMNANME in (XYZ,ABC)
            ) p


Thank you for the helps from all to reach at unpivot concept


这篇关于通过其名称为第一个表的行名称的另一个表中的selectiong值更新表的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆