Showing posts with label SQL Queries. Show all posts
Showing posts with label SQL Queries. Show all posts

Sunday, December 4, 2011

Copy table from one database to another database

Example:

             SELECT * INTO db1.dbo.table1
             FROM db2.dbo.table2

Please mind that this query only copies table schema and data only.

All constraints, indexes, statatics, you need to use alternatives 

Database BackUp and Restore Script

For .Net developer a very common task is to take reguler backup and restore of SQL Server Database. Most of the time developer does that thru UI of Sql Server Management Studio. It is acully nice to know the Scripts which we can run and take backup and restore easily.


       To BackUp :-      
     BACKUP DATABASE [DatabaseName] TO DISK = 'C:\FileName.bak' WITH FORMAT
       To Restore :-
           RESTORE DATABASE [DatabaseName] FROM DISK = 'C:\FileName.bak'


Also when ever you do any database opration thru UI of Sql Server Management Studio you can always have look to the Script behind that opration. Its good practise to look at the script run by Sql Server to do any database realted opration.

How to insert multiple records with single insert query


    USE [Demo]
         GO
    --Create Demo Table—
       
    CREATE TABLE DemoTable(Data VARCHAR(50))       

    --The way we used to—

    INSERT INTO DemoTable(Data)
        VALUES ('DATA 1');
    INSERT INTO DemoTable(Data)
        VALUES ('DATA 2');
    INSERT INTO DemoTable(Data)
        VALUES ('DATA 3');
    INSERT INTO DemoTable(Data)
        VALUES ('DATA 4');
       
       
Solution 1:

    CREATE TABLE DemoTable(Data VARCHAR(50))       


    INSERT INTO DemoTable(data)
        VALUES ('DATA 1'),('DATA 2'),('DATA 3'),('DATA 4');


Solution 2:

    CREATE TABLE DemoTable(Data VARCHAR(50))       

    INSERT INTO DemoTable(data)
    SELECT 'DATA 1'
    UNION ALL
    SELECT 'DATA 2'
    UNION ALL
    SELECT 'DATA 3'
    UNION ALL
    SELECT 'DATA 4'