插入选定的值

时间:2013-09-02 07:36:06

标签: sql sql-server

让表用户与vallues:

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 )

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

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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