我有这个查询,我正在使用两个表连接更新语句。这是我构建的查询:
DECLARE @DocHoldReasons VARCHAR(8000)
SET @DocHoldReasons = 'DocType Hold'
UPDATE dbo.EpnPackages
SET Error = 1, Msg = COALESCE (@DocHoldReasons + ': ', '') + cv.Value
FROM EpnPackages p
INNER JOIN EpnCountyValues cv ON cv.CountyId = p.CountyId and cv.ValueName = 'DocHoldReason'
WHERE p.Status = 1000
AND p.Error = 0
EpnCountyValues表中有两行具有相同的ValueName,我需要它们连接在一起,而且我很难做到这一点。我能得到的只是第一行的值。这就是我得到的字符串应该是什么样的 - 'DocType Hold:Test:Test.124。'
eidt:我需要连接具有相同ValueName的行以进行更新查询。 ValueName = DocHoldReason
可能有两行以上以下是EpnCountyValues表的结构:
CountyValueId CountyId ValueName Value
1 1 DocHoldReason Test
2 2 xyz Test1
3 3 DocHoldReason Test.124.
非常感谢任何帮助。谢谢!
答案 0 :(得分:0)
您可以加入EpnCountyValues表两次!
像这样,
DECLARE @DocHoldReasons VARCHAR(8000)
SET @DocHoldReasons = 'DocType Hold'
Select @DocHoldReasons + ': ' + ev1.Value + ': ' + ev2.Value
From EpnPackages p
Join EpnCountyValues ev1 on p.packageID = ev1.packageID
Join EpnCountyValues ev2 on ev1.ValueName = ev2.ValueName
Where ev1.ValueName = 'DocHoldRegion'
And p.status = 1000
And p.error = 0
那个选择看起来对你好吗?如果是,请运行更新。我总是尝试在更新之前运行一个选择。我不得不承认,为什么你加入了CountyID我有点困惑,但是看起来你似乎要更新来自不同郡的价值观?
答案 1 :(得分:0)
您可以通过在加入前预先聚合表来执行您想要的操作。如果只有两个值并且您不关心订单,那么这将起作用:
DECLARE @DocHoldReasons VARCHAR(8000);
SET @DocHoldReasons = 'DocType Hold';
UPDATE dbo.EpnPackages
SET Error = 1,
Msg = (COALESCE(@DocHoldReasons + ': ', '') + minv +
(case when minv <> maxv then ': ' + maxv else '' end)
)
FROM EpnPackages p INNER JOIN
(select cv.CountyId, min(cv.value) as minv, max(cv.value) as maxv
from EpnCountyValues cv
where cv.ValueName = 'DocHoldReason'
) cv
ON cv.CountyId = p.CountyId
WHERE p.Status = 1000 AND p.Error = 0;
编辑:
对于两个以上的值,您必须进行字符串连接。这在SQL Server中是“令人不快的”。这是方法:
DECLARE @DocHoldReasons VARCHAR(8000);
SET @DocHoldReasons = 'DocType Hold';
UPDATE dbo.EpnPackages
SET Error = 1,
Msg = (COALESCE(@DocHoldReasons + ': ', '') +
stuff((select ': ' + cv.value
from EpnCountyValues cv
where cv.ValueName = 'DocHoldReason' and
cv.CountyId = p.CountyId
for xml path ('')
), 1, 2, '')
)
WHERE p.Status = 1000 AND p.Error = 0;
此版本使用相关子查询而不是使用聚合的连接来执行此操作。
编辑II:
您可以使用其他coalesce
:
DECLARE @DocHoldReasons VARCHAR(8000);
SET @DocHoldReasons = 'DocType Hold';
UPDATE dbo.EpnPackages
SET Error = 1,
Msg = (COALESCE(@DocHoldReasons + ': ', '') +
COALESCE(stuff((select ': ' + cv.value
from EpnCountyValues cv
where cv.ValueName = 'DocHoldReason' and
cv.CountyId = p.CountyId
for xml path ('')
), 1, 2, ''), '')
)
WHERE p.Status = 1000 AND p.Error = 0;