2012-08-28 73 views
0

有人能幫助請我不知道我做錯了:SQL腳本句法和語法問題

IF EXISTS (SELECT name 
     FROM sys.tables 
     WHERE name = N'MemberIdsToDelete') 
DROP TABLE [MemberIdsToDelete]; 
GO 

SELECT mm.memberid , 
     mm.aspnetuserid , 
     mm.email , 
     mm.RowNum AS RowNum 
INTO #MemberIdsToDelete 
FROM membership.members AS mm 
     LEFT JOIN aspnet_membership AS asp ON mm.aspnetuserid = asp.userid 
     LEFT JOIN trade.tradesmen AS tr ON tr.memberid = mm.memberid 
WHERE asp.isapproved = 0 
     AND tr.ImportDPN IS NOT NULL 
    AND tr.importDPN <> '' 
ORDER BY mm.memberid 

DECLARE @MaxRownum INT 
SET @MaxRownum = (SELECT MAX(RowNum) 
        FROM  #MemberIdsToDelete 
       ) 

DECLARE @Iter INT 
SET @Iter = (SELECT MIN(RowNum) 
       FROM  #MemberIdsToDelete 
      ) 

DECLARE @MemberId INT 
DECLARE @TrademId INT 
DECLARE @UId UNIQUEIDENTIFIER 
DECLARE @Successful INT 
DECLARE @OutputMessage VARCHAR(200) 
DECLARE @Email VARCHAR(100) 
DECLARE @Username VARCHAR(100) 

SELECT @MemberId = memberId , 
     @UId = AspNetUserId 
FROM MemberIdsToDelete 
SELECT @TrademId = TradesManId 
FROM trade.TradesMen 
WHERE memberId = @MemberId; 

WHILE @Iter <= @MaxRownum 
    BEGIN 
    SELECT * 
    FROM #MemberIdsToDelete 
    WHERE RowNum = @Iter 
    --more code here 
    SET @Iter = @Iter + 1 
    END 

我只是想檢查我的表MemberIdsToDelete存在,如果是這樣砸, 與創建MemberIdsToDelete結果從通過MemberIdsToDelete表的SELECT 迴路設置和執行操作

我收到錯誤ROWNUM不存在

回答

0

一開始,來檢查表是否存在,然後相應地下降,你需要使用像

IF EXISTS (SELECT name 
      FROM sys.tables 
      WHERE name = N'MemberIdsToDelete') 
DROP TABLE [MemberIdsToDelete]; 
GO 

爲錯誤,當您嘗試引用它的ROWNUM列不存在。將它包含在SELECT語句中

select mm.memberid, mm.aspnetuserid, mm.email, mm.RowNum AS RowNum  
into #MemberIdsToDelete  
from membership.members as mm  
    left join aspnet_membership as asp  
     on mm.aspnetuserid=asp.userid  
      left join trade.tradesmen as tr  
       on tr.memberid=mm.memberid  
where asp.isapproved = 0 and tr.ImportDPN IS NOT NULL 
    and tr.importDPN <> '' 
order by mm.memberid; 
GO 

我希望這有助於。

編輯。根據您的評論的額外錯誤。您現在正試圖訪問不存在的臨時表。在嘗試讀取臨時表之前,您必須首先填充臨時表#MemberIdsToDelete。無效列錯誤歸結於同樣的問題。您正嘗試從不存在的臨時表中讀取名爲RowNum的列。

Edit2。從#MemberIdsToDelete刪除'#'。您正在插入表格而不是臨時表格。或者,在上面的select into上添加#(參見上面的代碼)。這將使其成爲臨時表格。

+0

我仍然收到錯誤:無效的列名'RowNum'。和無效的對象名稱'#MemberIdsToDelete'關於如果存在,yikes我知道MySql向後但sql是另一回事:) –

+0

請參閱編輯我的答案... – MoonKnight

+0

謝謝,所以爲了創建臨時表,我可以只是運行選擇?我試過,仍然有錯誤無效的列名「RowNum' –

0

您沒有在表中的列ROWNUM。

嘗試:

選擇mm.memberid,mm.aspnetuserid,mm.email,ROW_NUMBER()OVER(ORDER BY(選1))作爲ROWNUM ....

這應該解決您的問題,但我不會推薦這種循環刪除的想法。