UPDATE
dbo.FormDetail
SET
FieldOrder=FieldOrder+1
WHERE
WHERE DocCode IN (1,2,3)
AND FieldOrder >= (SELECT FieldOrder FROM dbo.FormDetail
WHERE FieldData LIKE '%OldField%'
AND DocCode IN (1,2,3))
不知道我在这里尝试做的有多清楚,但是我想在FieldOrder
表中为FormDetail
表增加一些文档,但仅限于某个字段之后(基本上所以我有一个空隙来插入一个新的领域)。但显而易见的问题是,我FieldOrder
中的Where
不会特定于该语句当前可能正在更新的文档。我认为可能使用分区,但我只在partitions
部分使用From
。任何帮助都会非常感激。
更新
dbo.FormDetail示例数据
DocCode FieldOrder FieldData
1 1'标题'
1 2'OldField'
1 3'签名'
2 1'段落'
2 2'OldField'
3 1'OldField'
答案 0 :(得分:2)
在现有代码中,您的子查询会执行一次并将所有结果返回到外部查询。
您实际看起来想要的是对于外部查询正在处理的每一行执行一次子查询。它被称为相关子查询。
为了让它像我一样工作,我做了两处改变;
我在子查询中给了表一个别名
2.我已经更改了子查询WHERE子句以引用外部查询
UPDATE
dbo.FormDetail
SET
FieldOrder=FieldOrder+1
WHERE
DocCode IN (1,2,3)
AND FieldOrder >= (SELECT lookup.FieldOrder
FROM dbo.FormDetail AS lookup
WHERE lookup.FieldData LIKE '%OldField%'
AND lookup.DocCode = FormDetail.DocCode
)
另一种选择可能是加入子查询...
UPDATE
FormDetail
SET
FieldOrder=FieldOrder+1
FROM
dbo.FormDetail
INNER JOIN
(
SELECT
DocCode,
FieldOrder
FROM
dbo.FormDetail
WHERE
DocCode IN (1,2,3)
AND FieldData LIKE '%OldField%'
)
AS lookup
ON lookup.DocCode = FormDetail.DocCode
AND lookup.FieldOrder >= FormDetail.FieldOrder
答案 1 :(得分:0)
你得到什么错误?我唯一看错的是你不限制你的子查询。在大型数据集上,它可能有点低效,但目前您需要的只是一个MIN();
DECLARE @FormDetail TABLE(
DocCode INT
, Fieldorder INT
, FieldData NVARCHAR(MAX)
)
INSERT INTO @FormDetail (DocCode, FieldOrder, FieldData) VALUES (1,1, 'Title')
INSERT INTO @FormDetail (DocCode, FieldOrder, FieldData) VALUES (1,2, 'OldField')
INSERT INTO @FormDetail (DocCode, FieldOrder, FieldData) VALUES (1,3, 'Signature')
INSERT INTO @FormDetail (DocCode, FieldOrder, FieldData) VALUES (2,1, 'Paragraph')
INSERT INTO @FormDetail (DocCode, FieldOrder, FieldData) VALUES (2,2, 'OldField')
INSERT INTO @FormDetail (DocCode, FieldOrder, FieldData) VALUES (3,1, 'OldField')
UPDATE @FormDetail SET
FieldOrder = FieldOrder + 1
WHERE
DocCode IN (1,2,3)
AND FieldOrder >= (
SELECT MIN(FieldOrder) FROM @FormDetail
WHERE FieldData LIKE '%OldField%'
AND DocCode IN (1,2,3)
)
SELECT * FROM @FormDetail
给出以下内容:
1 2标题
1 3 OldField
1 4签名
2 2段
2 3 OldField
3 2 OldField
你想要的只是在某一点之后增加你的田径顺序,对吗?