Thursday, June 10, 2010

Merge SQL tables

Let say, I have two tables:
table1:(Fields:PersonID, FirstName, LastName, Role, Department)
table2:(fields: PersonID, Unit).

and I want to create a new table with these fields:
table: ( Fields:PersonID, FirstName, LastName, Role, Department, Unit).

here is the query:

SELECT table1.*, table2.Unit
INTO new_table_name
FROM table1 inner join table2
on table1.PersonID = table2.PersonID

If table1 and table2 has one-to-many relation then first
use this postto make it one-to-one relaion; otherwise it'll create multiple PersonID into new table, which you don't want.

Wednesday, May 26, 2010

Bind stored procedure data into Gridview

First, let's create a stored procedure with a name: 'Dynamic_table'
and sqlconnection 'conn' and then do the following:

SqlCommand cmd = new SqlCommand("Dynamic_table", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@tableName",
SqlDbType.VarChar).Direction = ParameterDirection.Input;
cmd.Parameters["@tableName"].Value = Session["tableValue"];

cmd.Connection.Open();

SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);

GridView1.DataSource = dt;
GridView1.DataSourceID = string.Empty;
GridView1.DataBind();
cmd.Connection.Close();

Happy Programming !!!

Stored Procedure to select dynamic table @ runtime

Create Proc Dynamic_table
@tableName varchar(50)

as

begin


declare @sql nvarchar(100)

Set @sql='Select * from '+@tableName

exec sp_executesql @sql

end

Tuesday, May 25, 2010

SQL query to add Zero prefix

Let say,
I have a Database column 'ISSN' and data in it, should be 8 digits long. When I import data from excel to SQL table, it truncates the initial 1-3 zeros because it doesn't like zero as first digits when you mark the column as int but if you mark as text that's fine.
Now, let's write SQL query so that if the ISSN is 5 digits long then add 3 zeros to prefix.
e.g If the ISSN is 45678 then it should be '00045678'
If it is 6 digits long, then add two zeros to prefix....If 8 digits long keep as it is.
Hence, the SQL query is:

update table
set ISSN = RIGHT('00000000'+ISSN,8)

Happy Programming !!!