17 June 2013

Different ways of inserting records into tables using SQL query

Method 1:

Insert one row at a time,
create table EmpDtl1(EmpId int,EmpName varchar(30))                
insert into EmpDtl1 values(1,'one')
Method 2:

Insert rows into table retuned by the query
insert into EmpDtl1            
select * from EmpDtl2
Here condition is number of columns and respective data types returned in select statement should match with insert table schema 

Method 3: 

Insert query result into new table
select * into EmpCopy from EmpDtl1
* into <New Table> clause is used for copy the result set into new table.
similartly,
select * into #tmpEmpCopy from EmpDtl1
Note:Inserting table in this query should not exist in database before executing this query. 

Method 4:

 Insert rows into table returned by stored procedure
insert into EmpDtl1            
exec spGetEmpDetails
Here, number of columns returned by stored procedure shoud match with the inserting table(EmpDtl1)
Note: It is not possible to insert stored procedure result set data into new table so create a table based on the result set returned by the stored procedure

No comments:

Post a Comment