1

在我的 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参数的身份?

4

2 回答 2

1

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

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

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

链接到小提琴

于 2012-07-08T09:01:27.933 回答
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(Named Rep1) 中的第一个 With 之后使用另一个 With 子句我转换行返回两个逗号分隔的列。你可以改变你的需要。

于 2012-07-08T13:23:54.613 回答