0

拥有具有价值的表用户

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

有我从这个表中选择值的过程,然后想要排序并插入到另一个表中,我这样做:

SELECT @firstName = FirstName ,lastName = LastName ,@age = Age FROM dbo.users
if @age = 20
insert into tbl1(FirstName,LastName) values (@firstName,@LastName )
if @age = 21
insert into tbl2(FirstName,LastName) values (@firstName,@LastName )
if @age = 22
insert into tbl3(FirstName,LastName) values (@firstName,@LastName )

当我这样做时,所有行都不会插入到表中,我认为需要循环或其他东西来做,有人可以帮助我吗?我想在没有光标的情况下进行

4

2 回答 2

8

将这些代码包装在您的过程中。

insert into tbl1(FirstName,LastName) SELECT FirstName ,LastName FROM dbo.users WHERE Age = 20;
insert into tbl2(FirstName,LastName) SELECT FirstName ,LastName FROM dbo.users WHERE Age = 21;
insert into tbl3(FirstName,LastName) SELECT FirstName ,LastName FROM dbo.users WHERE Age = 22;
于 2013-09-02T07:38:54.700 回答
0
    begin tran

    declare @firstName varchar(20)
    declare @lastName varchar(20)
    declare @age int

    SELECT @firstName = firstName,
                 @lastName = lastName,
                 @age = Age 

    FROM dbo.users

    if @age = 20
    begin
    insert into tbl1
    select @firstName,@LastName from dbo.users where @age = 20
    end

    if @age = 21
    begin
    insert into tbl2
    select @firstName,@LastName from dbo.users where @age = 21
    end

    if @age = 22
    begin
    insert into tbl3
    select @firstName,@LastName from dbo.users where @age = 22
    end

    --check
    select * from tbl1
    select * from tbl2
    select * from tbl3

rollback tran

--commit tran
于 2013-09-02T07:54:56.477 回答