sql server存儲過程實現批量刪除


在項目中用到了存儲過程來進行批量刪除的操作,給大家分享一下

原理就是把id組成的字符串在數據庫分割成數組放一張臨時表,刪除的時候與id進行對照

--刪除會員信息
if OBJECT_ID('pro_DelUserInfo','p')is not null   --判斷存儲過程是否存在
    drop proc pro_DelUserInfo    --存在則刪除
go
create proc pro_DelUserInfo(   --創建存儲過程
@strid varchar(max)  --參數  格式 "1,2,3,5,6"
)
as  
declare @temp Table (a varchar(100))   --創建臨時表
begin

--把參數@strid分割成int數組並插入臨時表@temp
Declare @i Int
Set @strid = RTrim(LTrim(@strid))
Set @i = CharIndex(',',@strid)
While @i >= 1
Begin
Insert @temp Values(Left(@strid,@i-1))
Set @strid = SubString(@strid,@i+1,Len(@strid)-@i)
Set @i = CharIndex(',',@strid)
End
If @strid <> ''
Insert @temp Values (@strid)     --插入臨時表


delete tbl_User where id in (select * from @temp)  --執行為刪除操作 通過id與臨時表中的int數組對照

end


當然如果有多個表使用的話,也可以吧表名和唯一標示id寫成參數操作


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM