2012-07-08 56 views
1

在我的T-SQL代碼,我使用WITH從表中讀取數據。看完後,我想用WHILE擺脫WITH結果項(第一項,第二項,...),並從中刪除項目。如何使用循環(WHILE語句)的「WITH」子句的結果(TSQL)?

請看看我的代碼:

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

我認爲你正在尋找的財產以後這樣 :

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 

我在第二個用另一種隨着第一條後的帶(命名REP1) 我轉換行返回兩個逗號塞佩額定colomn。 你可以改變你的需要。

+0

原代碼刪除條目... – Lucero 2012-07-09 01:14:07

1

通用表表達式(WITH ...)只能先單SELECTUPDATEINSERTDELETEMERGE語句。但是,你的代碼似乎對於它的功能非常複雜。

這應該做同樣的代碼,但它是非常有效得多:

DECLARE @delSubjects TABLE (
    id int NOT NULL 
); 
DELETE BookSubjects 
    OUTPUT DELETED.SubjectID INTO @delSubjects 
    WHERE [email protected]; 
SET @result = (
    SELECT id+' ' 
    FROM @delSubjects 
    FOR XML PATH('') 
); 

Link to Fiddle