根据子查询更新每一行(sql server)

时间:2018-03-23 09:45:16

标签: sql sql-server

我想根据table2值

更新table1-> keyField的每一行

表1

Id|keyField

1|test_500

2|test_501

3|test_501

500,501是我的另一个表2的主键

表2

Id|value

500|A

501|B

502|C

我尝试了类似

的内容
update table1 set keyField=(select value from table2 where id=substring(expression))

但我的select返回多个语句,因此无法运行查询。 有什么帮助或指示吗?

3 个答案:

答案 0 :(得分:0)

您可以使用这样的语法

 UPDATE table1 SET keyField = Table2.Value 
 FROM table1 INNER JOIN table2 
 ON table1.Id = substring(expression)) 

答案 1 :(得分:0)

如果我做对了,这可能就是你所需要的:

UPDATE T1 SET
    keyField = T2.Value
FROM
    Table1 AS T1
    INNER JOIN Table2 AS T2 ON T2.id = SUBSTRING(T1.keyField, 6, 100)

在将子字符串结果与数值进行比较时要小心,可能会出现转换错误。

答案 2 :(得分:0)

尝试此代码(必要的注释在下面的评论中):

--generate some sample data (the same as you provided)
declare @table1 table (id int, keyField varchar(10))
insert into @table1 values (1,'test_500'),(2,'test_501'),(3,'test_502')
declare @table2 table (id int, value char(1))
insert into @table2 values (500,'A'),(501,'B'),(502,'C')
--in case you want to see tables first
--select * from @table1
--select * from @table2

--here you extract the number in first table in keyField column and match it with ID from second table, upon that, you update first table
update @table1 set keyField = value from @table2 [t2]
where cast(right(keyfield, len(keyfield) - charindex('_',keyfield)) as int) = [t2].id

select * from @table1