如何对“WITH”子句结果(sql)使用循环(WHILE语句)?

时间:2012-07-08 08:28:23

标签: tsql

在我的T-SQL代码中,我使用WITH来从表中读取数据。阅读后,我希望使用WHILEWITH结果中获取项目(第一项,第二项,......)并从中删除项目。

请参阅我的代码:

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参数定义身份?

2 个答案:

答案 0 :(得分:1)

公用表格式(WITH ...)只能位于单SELECTUPDATEINSERTDELETEMERGE语句之前。但是,您的代码似乎非常复杂。

这应该与您的代码相同,但效率更高:

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('')
);

Link to Fiddle

答案 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。 你可以改变你的需要。