使用其他表中的2 table-col更新1 table-col

时间:2017-01-30 07:41:05

标签: sql sql-server stored-procedures

是否可以使用其他表中的1 column/field更新我的表格2 column/field

我尝试了这个查询:

UPDATE TEMP_Quantity
SET SS = (SELECT Qty1, Qty2 FROM Table_Quantity
WHERE Id = @IdHolder AND ProductId = 7)
WHERE Id = @IdHolder

并且Sql说这个错误:

  

当子查询没有引入EXISTS时,只能在选择列表中指定一个表达式。

SS = NVarchar(因为它可以接受我将选择的列上的数字或字符串)

有人能告诉我正确的方法吗? tia:)

3 个答案:

答案 0 :(得分:1)

嗯...回答你的问题,你可以CONCAT两个数量的

UPDATE t1
SET SS = CONCAT(t2.Qty1, t2.Qty2) 
FROM TEMP_Quantity t1 
INNER JOIN Table_Quantity t2 on t2.Id = t1.Id
WHERE t1.Id = @IdHolder
AND  t2.ProductId = 7

但这只是感觉不对。

答案 1 :(得分:1)

试试这个:

UPDATE TEMP_Quantity
SET SS = (SELECT CAST(Qty1 AS VARCHAR(10)) + CAST(Qty2 AS VARCHAR(10)) 
          FROM Table_Quantity
          WHERE Id = @IdHolder AND ProductId = 7)
WHERE Id = @IdHolder

答案 2 :(得分:0)

您可以使用并检查以下脚本。我希望,它对你有用。

declare @qty1 int
declare @qty2 int

if object_id('tempdb..#dbDestination') is not null
    drop table #dbDestination

create table #dbDestination(
Id int,
ss nvarchar(50)
)

if object_id('tempdb..#dbSource') is not null
    drop table #dbSource

create table #dbSource(
Id int,
ProductId int,
qty1 int,
qty2 int
)

insert into #dbDestination(Id,ss) values (1,null),(2,null)
insert into #dbSource(Id,ProductId,qty1,qty2) values(1,7,10,3), (2,null,8,2)

UPDATE #dbDestination
SET SS = (
            SELECT CAST(qty1 as nvarchar(50))+ cast(qty2 as nvarchar(50)) 
            FROM #dbSource
            WHERE Id = 1 AND ProductId = 7
        )
WHERE Id = 1

select * from #dbDestination