this blog contains information for .net and sql stuffs. You can find various tips and tricks to overcome problem you may be facing in ...

Friday, March 19, 2010

Simple SQL Operation

Yes in this post you will see many a things of SQL Server which is very small; it may be useful in our day to day life.

Firstly just imagine you want to insert values in table, certainly you go for below approach. Let me create a table for our testing

CREATE TABLE MyTable(TestName VARCHAR(25))

Now for data insert you use ..

INSERT INTO MyTable(TestName)

VALUES ('ONE')

GO

INSERT INTO MyTable(TestName)

VALUES ('TWO')

GO

But you can do achieve same thing with below script where we have used UNION ALL

INSERT INTO MyTable(TestName)

SELECT 'ONE'

UNION ALL

SELECT 'TWO'

UNION ALL

SELECT 'THREE'

UNION ALL

SELECT 'FOUR'

UNION ALL

SELECT 'FIFVE'

UNION ALL

SELECT 'SIX'

GO

Hope this makes sense when we want to insert multiple records in table

Now let’s Go through another game, yes of-course this is some kind of game, you are playing in SQL server.

We want to insert Record to table from another table.

At that time we have two choices ( I am assuming that you have created table from above script and we will use that table in our below example)

1) New table is already created and you want to insert data in it.

CREATE TABLE MyTestTable(TempName VARCHAR(25))

INSERT INTO MyTestTable(TempName)

SELECT TestName FROM MyTable

SELECT * FROM MyTestTable

DROP TABLE MyTestTable

2) You want to create table at the time of insertion operation no table exists before it. In below MyTestTable is not created before but it will be created once we execute this

SELECT TestName

INTO MyTestTable

FROM MyTable

SELECT * FROM MyTestTable

DROP TABLE MyTestTable

No comments: