回答

收藏

T-SQL:遍历一组已知值

技术问答 技术问答 1525 人阅读 | 0 人回复 | 2023-09-14

这是我的情况:1 p* x6 R7 R7 U3 X4 j" k$ b! @- a
假设我有一个存储过程,我需要存储过程中,我需要id调用另一个存储过程。有没有办法做到这一点?
  Y( b( B! W4 `& P1 o而不是这样做:
# q; F) i0 L2 `5 P2 S; N# Q" Z5 Fexec p_MyInnerProcedure 4exec p_MyInnerProcedure 7exec p_MyInnerProcedure 12exec p_MyInnerProcedure 22exec p_MyInnerProcedure 19做这样的事:
8 _# O5 f% F/ A) ?7 o*magic where I specify my list contains 4,7,12,22,19*DECLARE my_cursor CURSOR FAST_FORWARD FOR*magic select*OPEN my_cursor FETCH NEXT FROM my_cursor INTO @MyIdWHILE @@FETCH_STATUS = 0BEGINexec p_MyInnerProcedure @MyIdFETCH NEXT FROM my_cursor INTO @MyIdEND我在这里的主要目标是维护(随着业务的变化很容易删除/添加)ID),能够在一行列出一切ID …性能不应该成为大问题3 {; \1 m0 i; c1 e  [9 c
                                                                ! o5 X& x. u1 y2 ~# ?3 s  @
    解决方案:                                                               
# s2 Y( P+ G4 S  |                                                                declare @ids table(idx int identity(1,1),id int)insert into @ids (id)    select 4 union    select 7 union    select 12 union    select 22 union    select 19declare @i intdeclare @cnt intselect @i = min(idx) - 1,@cnt = max(idx) from @idswhile @i < @cntbegin     select @i = @i  1     declare @id = select id from @ids where idx = @i     exec p_MyInnerProcedure @idend
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则