基于单独表条件的 SQL 更新列

丹·奥尔洛夫斯基

我的任务是更新数据库中的几个条目。

两个表需要通过 Id 连接。一个是帐户表,另一个是区域表。

我在 Account 表中有一个 TerritoryID,并且该条目必须使用基于它的 DisplayName 的地区的 Id 进行更新。

账户表

AccountId
TerritoryId << 我需要填充它。

领土表
标识
显示名称

我有一个包含 AccountId 和 DisplayNames 的电子表格。我需要一个查询,该查询将根据一个条件 (accountId) 使用基于另一个表中的另一个条件(基于 DisplayName)的值更新一个表。

我一直在尝试类似的事情:

UPDATE 
 [dbo].[Account] 
SET 
 TerritoryId = [dbo].[Territories].Id 
FROM Accounts ON WHERE AccountId = '6477026' SELECT Id FROM Territories WHERE DisplayName LIKE '%partialDisplayName'

我也试图CASE在那里整合一个声明。不过,我似乎无法坚持下去。我发现的潜在重复答案并没有考虑两个单独表中的两个条件

亚当

以下是你的问题的捏造。你的桌子...

create table #account (
  accountId int not null primary key
, territoryID int null
)

create table #territory (
  territoryId int not null primary key
, displayName varchar(20)
)

一些示例数据...

insert into #territory values (1, 'Hell');
insert into #territory values (2, 'heaven');
insert into #territory values (3, 'purgatory');

insert into #account values (1, 0)
insert into #account values (2, 0)
insert into #account values (3, 0)
insert into #account values (4, 0)
insert into #account values (5, 0)
insert into #account values (6, 0)
insert into #account values (7, 0)
insert into #account values (8, 0)

我有一个包含 AccountId 和 DisplayNames 的电子表格。我需要一个查询,该查询将根据一个条件 (accountId) 使用基于另一个表中的另一个条件(基于 DisplayName)的值更新一个表。

选项 1:在 excel 中,制作更新语句,将这些语句从 Excel 复制到您的查询编辑器,然后运行它们。查询如下所示:

UPDATE #account
SET territoryID = (SELECT territoryId FROM #territory WHERE displayName = '<name>')
WHERE accountID = <id>

选项 2:您将电子表格的内容导入 Excel(有很多方法可以做到这一点,Google 是您的朋友)。

--Create table to store the temp data
CREATE TABLE #excel_stuff (accountId int, displayName varchar(20));

--Created insert statements for the data from the spreadsheet. Running
--the inserts.
insert into #excel_stuff values (1, 'heaven')
insert into #excel_stuff values (2, 'heaven')
insert into #excel_stuff values (3, 'hell')
insert into #excel_stuff values (4, 'heaven')
insert into #excel_stuff values (5, 'heaven')
insert into #excel_stuff values (6, 'purgatory')
insert into #excel_stuff values (7, 'purgatory')
insert into #excel_stuff values (8, 'hell')

此时,您的 Excel 数据已在数据库中。现在,我将更新 #account 表中的 regionId 值:

UPDATE #account
SET territoryID = (
SELECT t.territoryID
FROM #excel_stuff ex INNER JOIN #territory t
ON ex.displayName = t.displayName
WHERE ex.accountId = #account.accountId
)

DROP TABLE #excel_stuff;

祝你好运!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章