SQL clone / copy and swap database tables

code, database, SQL

have you ever had a database table that you needed to clone? you can use any number of convoluted methods such as: manually coping and pasting rows in the database manager, running lots of queries/stored procedures, or writing a script to cycle though each row copying data from one table to the next. all of these methods are inferior and far more complex then the method im going to show you.

introducing the select into query...
this method should be used if the table you want to clone exists, but the new table douse not. the select into query will create the new table for you, copying all the column names, properties, and data. if you want to make an exact clone of the table you can select * into the new table. but if you only want a few specific columns, you can declare only the ones you want. the syntax is elegantly simple...

    SQL procedure
  1. SELECT *
  2. INTO [new-table]
  3. FROM [old-table]

this is a great solution for cloning a table. it's fast and lightweight since its all executed on the database end, not straddled between middleware.

now here's another situation...
let's say we have a simple web-form that is submitting 4 pieces of data: username, date, value1, and value2. this form has been collecting data for a long time, and all of a sudden you realize that somehow your save procedure has swapped the data for value1 and value2! some people might just dive into the table and start modifying rows. but im paranoid. i like to validate my SQL procedures before i destroy an entire table's worth of data. we can use the same clone table technique above to make a copy of the table, but we can go a step further and also swap the data in value1 and value2 in the same procedure.

    SQL procedure
  1. SELECT *
  2. INTO [new-table]
  3. FROM [old-table]
  4.  
  5. DECLARE @temp AS decimal
  6. UPDATE [new-table]
  7. SET @temp=value1, value1=value2, value2=@temp

basically we have 2 SQL statements in one here. the first will clone old-table into new-table. the second declares a temporary variable and uses the temp var to switch the data in value1 and value2 in the new-table.

if you only need to switch values for a smaller portion of the dataset, say all rows with an id value less than a certain number, you can simply add a where clause to the end of your statement.

    SQL procedure
  1. SELECT *
  2. INTO [new-table]
  3. FROM [old-table]
  4.  
  5. DECLARE @temp AS decimal
  6. UPDATE [new-table]
  7. SET @temp=value1, value1=value2, value2=@temp
  8. WHERE id < 806

this will copy the entire table into the new one, but only swap the values for ids less than 806. all other values will be cloned exactly.

inline SQL statements

code, database, SQL

the world of database programming can be a dark and treacherous journey. when you first set out, your quest seems manageable. but as time progresses your start to realize you need more queries, more tables, etc, etc, to achieve your goal. well today im going teach you a little trick that might help you need one less stored procedure then you thought...

sometimes its true, you actually do need two queries to get the job done. but other times you can circumvent this by using something like a "join" or "inner join" query to merge two tables together and pull your results from both.

but still, sometimes this isnt enough...

so lets say you need to first get an automatically generated ID number from a table and you need two parameters to get this data. then you need a subsequent query to update that record.

historically, i probally would have said that you need to run two separate SQL procedures to achieve this goal. but if i would say that now, id be a liar...

take a look at this:

    SQL stored procedure
  1. CREATE PROCEDURE [dbo].[TESTING-UPDATE]
  2.    (@who           [nvarchar](50),
  3.     @which          [nvarchar](50))
  4.  
  5. AS UPDATE [dbo].[table-name]
  6. SET someValue = 'new value'
  7. FROM (
  8.         SELECT TOP 1 (autoid) as nuID
  9.         FROM [dbo].[table-name]
  10.         WHERE name = @user AND num = @which
  11.         ORDER BY autoid DESC
  12.       ) as tested
  13. WHERE autoid = tested.nuID
  14. GO

as you can see, im actually running two queries in one!
the traditional FROM [table-name] statement has been replaced by an "inline SQL query". what happens is the database will see the FROM () parenthetical notation, and immediately execute the syntax between them. that statement then returns its result set into a named object (in this case its called "tested"). then the rest of the procedure will execute as normal, but with the additional data we got from our inline query.

this technique can be extremely powerful! i just learned about it this week and i have already removed 10 now unnecessary SQL queries from the database for a project at work. so keep that one in you SQL lexicon for later ;D

asp.net pure code database connection

code, database, dotnet, C#, tutorial, SQL

visual studio 2005 has a tool for connecting to a database called a "sqlDataSource". while this tool works, i find myself wanting to create the connection and build or execute stored procedures within my own C# code. this tutorial will show you how to connect to a sql database 3 different ways in asp.net

the first thing is creating a connection with your database. if you understand how connection strings are built, write your own other wise will can use the visual studio database tool to do that for us.

drag a new sqlDataSource onto the canvas, highlight it, then click the little arrow that appears to reveal configure datasource. in the windows that follow you can create a new database connection (or use an existing one). refresh the server list and select your database server (or localhost). then chose if you want to use windows integrated security (where the server is the database user) or sql server security (where you supply the sql username and password). then select the database you want to connect to on the server, and test your connection.

press ok, and you will return to the previous window, click the little plus sign to expand and show you the connection string that visual studio generated for you. copy it, and click cancel. now you can delete the sqlDataSource and switch to code view.

now the first thing we need to do is create a database connection in our code

    asp.net c# code
  1. SqlConnection con = new SqlConnection("Data Source=DEVELOPMENT;Initial Catalog=rss;Integrated Security=True");
  2.  
hardcoded procedure
    asp.net c# code
  1. int id = 13;
  2. con.Open();
  3. //-create procedure
  4. string select = "SELECT * FROM 'table' WHERE 'id' = @ID";
  5. SqlCommand command = new SqlCommand(select, Con);
  6. //-paramerter adding
  7. command.Parameters.Add("@ID", SqlDbType.Int).Value = id;
  8. //-make a data reader
  9. SqlDataReader reader = command.ExecuteReader();
  10. while (reader.Read())
  11. {
  12. String data = reader["thing"].ToString();
  13. }
  14. //-close connection
  15. con.Close();
using a stored procedure with one parameter
(ie: "DELETE 'tabelname' WHERE 'id' = @ID; ")
    asp.net c# code
  1. int id = 42;
  2. con.Open();
  3. //-setup query
  4. SqlCommand commando = new SqlCommand("deleteUser", con);
  5. commando.CommandType = CommandType.StoredProcedure;
  6. //-paramerter adding
  7. commando.Parameters.Add("@ID", SqlDbType.Int).Value = id;
  8. //-execute the query
  9. commando.ExecuteNonQuery();
  10. con.Close();
using a stored procedure without any parameters
(ie: "SELECT * FROM 'tabelname' ;")
    asp.net c# code
  1. con.Open();
  2. //-select a stored procedure
  3. SqlCommand commander = new SqlCommand("getFilename", con);
  4. commander.CommandType = CommandType.StoredProcedure;
  5. //-make a data reader
  6. SqlDataReader SQLreader;
  7. SQLreader = commander.ExecuteReader();
  8. while (SQLreader.Read())
  9. {
  10. //-select data by array index
  11. String data = SQLreader[0].ToString();
  12. //-select data by sql collumn name
  13. String data2 = SQLreader["name"].ToString();
  14. }
  15. //-close connections
  16. SQLreader.Close();
  17. con.Close();

getLastSqlID

database, code

here's a simple SQL script that returns the last row created. this is great for when you add a new record that has an autogenerated id and you need that number.

    sql server
  1. CREATE PROCEDURE [dbo].[getLastLogin]
  2. AS
  3. SELECT TOP 1 *
  4. FROM dbo.login
  5. ORDER BY id DESC
  6. GO
or if your an open source guy
    mySql
  1. SELECT * FROM `login`
  2. ORDER BY `id` DESC
  3. LIMIT 1,1;

MMVII .( xero harrison ) . http://the.fontvir.us/b10g
RSS syndication