Friday, September 9, 2011

INSERT in SQL Server

In SQL Server there are many ways to insert records into table. See below:

INSERT row by row:

INSERT INTO Table1 VALUES(1,’Rajesh’,10000);
INSERT INTO Table1 VALUES(2,’Mahesh’,20000);

INSERT records into temp table from existing table:

SELECT * INTO #tempTable
FROM Table1
--creates new temporary table and inserts data from existing table

INSERT records into new table from existing table:

SELECT * INTO Table2
FROM Table1
--creates new table and inserts data from existing table
--if Table2 already exists it gives error

INSERT records into existing table from another table:

insert into Table2
select * from Table1
--insert records into table from existing table.
--Throws error if table not exists

--This inserts data from one table to another if both tables exist

INSERT records into existing table from the Stored procedure’s returned result set:

insert into Table2
EXEC Table1_RECORDS
--inserts stored procedure returned records into table if table exists
--No.of Columns in Table2 and no.of Columns return by SP should be same.

SELECT * INTO #tempTable
EXEC Table1_RECORDS
--Gives Error

No comments:

Post a Comment