Sql 插入选定值
让表用户具有值:Sql 插入选定值,sql,sql-server,Sql,Sql Server,让表用户具有值: FirstName LastName Age A A 20 B B 21 C C 22 D D 21 E E 20 在这个过程中,我从这个表中选择值,然后要排序并插入到另一个表中,我这样做: SELECT @firstNam
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 )
当我这样做的时候,所有的行都不会插入到表中,我想需要循环或者做一些事情,有人能帮我吗?我想在没有光标的情况下完成它将这些代码包装到您的过程中
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;
不,他正在插入不同的程序tables@MahmoudGamal因为我想更改插入程序nad,会有一些程序我无法理解你想要什么??
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