如何使用if语句在存储过程中调用另一个过程

时间:2013-09-02 10:52:37

标签: sql sql-server

让表用户与vallues:

FirstName     LastName     Age
 A               A          20
 B               B          21
 C               C          22
 D               D          21
 E               E          20

然后我创建程序,在那里想检查年龄然后在if语句中调用另一个程序

SELECT @firstName = FirstName ,lastName = LastName ,@age = Age FROM dbo.users
if @age = 20
exec myProc1 'firstName','LastName'
if @age = 21
exec myProc2 'firstName','LastName'
if @age = 22
exec myProc3 'firstName','LastName'

当我调用此过程时if语句只占用一行然后再调用IF语句中的另一个过程,例如只能起作用

   if @age = 20
    exec myProc1 'firstName','LastName'

因为年龄= 20 是表格中的第一行。我想检查表中的所有行,怎么做?没有光标可以做到吗?

2 个答案:

答案 0 :(得分:1)

可以在没有光标的情况下执行此操作。但它仍然使用循环。

declare @t table as (id int identity(1, 1) primary key,
                     FirstName varchar(255),
                     LastName varchar(255),
                     Age int
                    );

insert into @t(FirstName, LastName, Age)
    select FirstName, LastName, Age
    from dbo.users;

declare @maxi int = (select max(id) from @t);

declare @i = 0, @FirstName varchar(255), @LastName varchar(255), @Age int;

while @i <= maxi
begin
    select @FirstName = FirstName, @LastName = LastName, @Age = age
    from @t
    where id = @i;
    if @age = 20
        exec myProc1 @firstname, @LastName;
    if @age = 21
        exec myProc2 @firstname, @LastName;
    if @age = 22
       exec myProc3 @firstname, @LastName;

    set @i = @i + 1;
end;

一些事情。首先,您并不需要临时表。获取循环计数器很方便。其次,我还假设您希望将变量作为三个存储过程的参数而不是常量字符串。

答案 1 :(得分:1)

创建table变量:

DECLARE @List TABLE(Id int IDENTITY(1,1), FirstName nVarchar(Max), LastName nVarchar(Max), Age INT)

然后在table变量

中插入所有数据
INSERT INTO @List (FirstName,LastName,Age)(SELECT FirstName, LastName, Age FROM YourTable)

DECLARE @intNumberOfRecords int, @intRowCount int, @FirstName nVarchar(Max), @LastName nVarchar(Max), @Age int
SET @intNumberOfRecords = @@ROWCOUNT
SET @intRowCount = 1  

WHILE @intRowCount <= @intNumberOfRecords  
BEGIN 


select @FirstName = FirstName, @LastName = LastName, @Age = age
from YourTable Where Id = @intRowCount 
if @Age = 20
    exec myProc1 @firstname, @LastName;
if @Age = 21
    exec myProc2 @firstname, @LastName;
if @Age = 22
   exec myProc3 @firstname, @LastName;

SET @intRowCount = @intRowCount + 1;

END

用户还可以在此处使用CASE声明,而不是if