在我的T-SQL代码中,我使用WITH
来从表中读取数据。阅读后,我希望使用WHILE
从WITH
结果中获取项目(第一项,第二项,......)并从中删除项目。
请参阅我的代码:
With Rep(SubjectId) As
(
SELECT [SubjectID] FROM [BookSubjects]
WHERE [BookID] = @BookID
)
WHILE EXISTS(SELECT [SubjectID] FROM Rep)
BEGIN
SELECT @SubjectID = SubjectID FROM Rep
SELECT @Result = @Result + CAST(@SubjectID AS varchar(10))
DELETE FROM Rep WHERE SubjectID = @SubjectID
END
我想我无法从WITH
删除项目结果!但我的另一个问题是如何将identity(1,1)
列设置为WITH
个参数?
在声明临时表中,我使用:
@ID Int Identity(1,1)
如何为WITH
参数定义身份?
答案 0 :(得分:1)
公用表格式(WITH
...)只能位于单SELECT
,UPDATE
,INSERT
,DELETE
或MERGE
语句之前。但是,您的代码似乎非常复杂。
这应该与您的代码相同,但效率更高:
DECLARE @delSubjects TABLE (
id int NOT NULL
);
DELETE BookSubjects
OUTPUT DELETED.SubjectID INTO @delSubjects
WHERE BookID=@BookID;
SET @result = (
SELECT id+' '
FROM @delSubjects
FOR XML PATH('')
);
答案 1 :(得分:1)
我认为你正在寻找像这样的事情 :
create table BookSubjects(SubjectID int,BookID int)
insert into BookSubjects(SubjectID ,BookID ) values(1,10)
insert into BookSubjects(SubjectID ,BookID ) values(2,20)
insert into BookSubjects(SubjectID ,BookID ) values(3,30)
insert into BookSubjects(SubjectID ,BookID ) values(4,40)
insert into BookSubjects(SubjectID ,BookID ) values(5,50)
insert into BookSubjects(SubjectID ,BookID ) values(6,60)
insert into BookSubjects(SubjectID ,BookID ) values(2,10)
insert into BookSubjects(SubjectID ,BookID ) values(2,10)
insert into BookSubjects(SubjectID ,BookID ) values(3,10)
insert into BookSubjects(SubjectID ,BookID ) values(4,10)
insert into BookSubjects(SubjectID ,BookID ) values(5,10)
insert into BookSubjects(SubjectID ,BookID ) values(6,10)
select * from BookSubjects
;With Rep As
(
SELECT [SubjectID],[BookID] FROM [BookSubjects]
WHERE [BookID] = 10
)
, Rep1 As
(
select
[BookID],
stuff((
select ',' + cast(t.[SubjectID] as varchar(100))
from Rep t
where Rep.[BookID] = t.[BookID]
order by t.[SubjectID]
for xml path('')
),1,1,'') as name_csv
from Rep
group by [BookID]
)
select * from rep1
我先使用另一个With子句,然后在第二个With(Named Rep1)中使用 我转换行返回两个逗号分隔的colomn。 你可以改变你的需要。