我有一个包含memberId的表,但它们不会同时运行。
我该如何循环使用它们?
我有这个:
select mm.memberid, mm.aspnetuserid, mm.email
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
ALTER TABLE #MemberIdsToDelete ADD id int NOT NULL AUTO_INCREMENT
DECLARE @MaxRownum int
SET @MaxRownum = (SELECT MAX(id) FROM MemberIdsToDelete)
WHILE @Iter <= @MaxRownum
-- do things
SET @Iter = @Iter + 1
END
以上不正确,我明显地在alter table行上出错了: 'AUTO_INCREMENT'附近的语法不正确
答案 0 :(得分:1)
ALTER TABLE
更改实际表格,而不是数据。在您添加数据后添加列没有意义,因此它可能不是您想要的。
您可以使用游标循环遍历任何结果集,但有关游标的两个重要规则:
CURSOR
表示您正在考虑SQL问题,因为它是一个程序代码问题 - 它可能是唯一的方法,但要避免它(即使做了其他事情,如果你不这样做,也可以在午餐后回来)。看到设定方法。在你说你需要从其他表中删除的评论中,这样做会更好:
delete from table1 where memberId in
(
select mm.memberid
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 <> ''
)
delete from table2 where memberId in
(
select mm.memberid
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 <> ''
)
delete from table3 where memberId in
(
select mm.memberid
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 <> ''
)
基于三组的操作本质上更快,查询分析器可以更好地为您进行优化,最重要的是,编写起来更简单。
答案 1 :(得分:0)
您可以使用游标循环遍历表格,如下所示:
DECLARE db_cursor CURSOR FOR SELECT Col1, Col2, -- your select query
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @Var1, @Var2, -- list of your variables based on select query
WHILE @@FETCH_STATUS = 0
BEGIN
-- do stuff
FETCH NEXT FROM db_cursor INTO @Var1, @Var2, -- list of your variables based on select query
END
CLOSE db_cursor
DEALLOCATE db_cursor
答案 2 :(得分:0)
也许Row_Number()更符合您的要求+我刚刚选择了很多对OP的评论:
SELECT
IDENTITY(INT,1,1) AS ID,
ROW_NUMBER() OVER (ORDER BY mm.memberid) AS RowN,
mm.memberid,
mm.aspnetuserid,
mm.email
INTO #MemberIdsToDelete
FROM
membership.members mm
INNER JOIN aspnet_membership asp
ON mm.aspnetuserid=asp.userid
INNER JOIN trade.tradesmen tr
ON tr.memberid=mm.memberid
WHERE
asp.isapproved <> 0
AND tr.importDPN <> ''
DECLARE @MaxRownum INT = (SELECT MAX(RowN) FROM MemberIdsToDelete)
DECLARE @Iter INT = 0
WHILE @Iter <= @MaxRownum
-- do things
SET @Iter = @Iter + 1
END