Tsql 不确定如何基于另一个表的内容填充表
我试着想办法解决这个问题,但我对tsql还比较陌生 这是我的两张桌子: 这是我的dbo.UsersAccountLink表: 这是我的公司。令牌表: 现在UsersAccountLink.CorporationId是空的,我需要根据Company.Token表中的内容填充它 因此,我需要遍历Company.Token表中的每条记录,获取Company.Token.TokenId值,然后使用TokenId查询Company.Token表,最后,我需要使用CorporationId更新dbo.UsersAccountLink表中的记录 最后,我想用Company.Token.CorporationId中的值更新dbo.UsersAccountLink.CorporationId 我希望这是有道理的 好吧,这是我到目前为止得到的。。。虽然不多,但我正在努力Tsql 不确定如何基于另一个表的内容填充表,tsql,sql-server-2012,Tsql,Sql Server 2012,我试着想办法解决这个问题,但我对tsql还比较陌生 这是我的两张桌子: 这是我的dbo.UsersAccountLink表: 这是我的公司。令牌表: 现在UsersAccountLink.CorporationId是空的,我需要根据Company.Token表中的内容填充它 因此,我需要遍历Company.Token表中的每条记录,获取Company.Token.TokenId值,然后使用TokenId查询Company.Token表,最后,我需要使用CorporationId更新dbo.Use
USE SuburbanPortal
go
-- Get the number of rows in the looping table
DECLARE @RowCount INT
SET @RowCount = (SELECT COUNT(*) FROM dbo.UsersAccountLink)
-- Declare an iterator
DECLARE @I INT
-- Initialize the iterator
SET @I = 1
-- Loop through the rows of a table @myTable
WHILE (@I <= @RowCount)
BEGIN
-- Declare variables to hold the data which we get after looping each record
DECLARE @CorpId UNIQUEIDENTIFIER, @TokenId UNIQUEIDENTIFIER
-- Get the data from table and set to variables
SET @TokenId = (SELECT [TokenId] FROM [SuburbanPortal].[dbo].[UsersAccountLink])
SET @CorpId = (SELECT [CorporationId] FROM [SuburbanPortal].[Company].[Token] WHERE @TokenId = ???)
-- Increment the iterator
SET @I = @I + 1
END
欢迎使用SQL Server。您的代码表明您来自一个编程背景,具有这种模式,称为“逐行咆哮”。业务的第一步是用join代替循环思维。不要在一个表中循环,然后在另一个表中搜索匹配项,而是使用join:
UPDATE UAL
SET UAL.CorporationId = T.CorporationId
FROM dbo.UserAccountLink UAL
INNER JOIN Company.Token T ON UAL.TokenId = T.TokenId