Sunday, April 25, 2010

::SQL Helpers

I will add some of the useful sql functions:

::COLUMN NAMES in a Table

select name from sys.columns
where object_id = OBJECT_ID(N'Sales.Orders');

::Information about schema views

lists the user tables in the current database along with their schema names
select table_schema, table_name, IST.TABLE_TYPE, IST.TABLE_CATALOG
from INFORMATION_SCHEMA.TABLES IST
--where TABLE_TYPE = N'Base table'

::List of tables in the database
exec sys.sp_tables;

::Waiting and Blocking Processes
Run this query at another query page and check waiting processes again with sys.dm_tran_locks

SELECT
  request_session_id                                  AS spid,
  resource_type                                       AS restype,
  resource_database_id                                AS dbid,
  DB_NAME(resource_database_id)                       as DBNAME,
  resource_description                                AS res,
  resource_associated_entity_id                       AS resid,
  CASE
      when resource_type = 'OBJECT' then  OBJECT_NAME( resource_associated_entity_id) 
      ELSE 'N/A'
  END  as ObjectName,
  request_mode                                        AS mode,
  request_status                                      AS status
FROM sys.dm_tran_locks
order by spid, restype;
 

Thursday, April 15, 2010

SQL Merging DATA

:::SQL MERGE

SQL server 2008 has a new feature to merge tables with actions for different conditions.

Here is an example for your reference:

MERGE INTO dbo.Target as TT
using dbo.Source as SS
    on TT.keyid = SS.keyid
WHEN MATCHED THEN
   UPDATE SET
     TT.col1 = SS.col1,
     TT.col2  = SS.col2,
     TT.col3 = SS.col3,
 WHEN NOT MATCHED THEN
  INSERT (col1,col2, col3,colX,colY )
  values (SS.col1,SS.col2,SS.col3,SS.colX,SS.colY);

--you need to use semicolon to finish the statement!

You can use merge statement to insert new table data to the existing table. You can also do the same operation with multiple insert, update , delete statements.

If you want to specify multiple conditions for matched case, you can do that.


MERGE INTO dbo.Target as TT
using dbo.Source as SS
 on TT.keyid = SS.keyid
 WHEN MATCHED AND (
  TT.col1 <> SS.col1
  OR TT.col2 <> SS.col2 )  THEN
UPDATE SET
     TT.col1 = SS.col1,
     TT.col2 = SS.col2
  WHEN NOT MATCHED THEN
     INSERT (col1,col2, col3,colX,colY )
        values (SS.col1,SS.col2,SS.col3,SS.colX,SS.colY);

You can update the related record, if it justifies your condition. You can monitor transactions with this statement. If there is a change in the record, you can add that to audit records.

:::HOW TO DELETE with TOP Option and USE ordering

Well, you might want to delete top 10 product reviews based on Ordering of low ratings. Ordering will not work directly. A logical ORDER BY for the top option in a modification statement is not allowed. When you say :

::>Delete top 10 from dbo.myreviews;

It will delete arbitrary records. if you want to order them, you can use table expressions.

WITH C as
(
   select top( 10 ) *
   from dbo.myreviews
   order by rating asc
)
DELETE FROM C;

Now, you got rid of the bad ratings for your product.

Wednesday, April 14, 2010

SQL : Deleting Data

I will add more sql related topics. How do we delete data?

::SQL Delete Statement
The standard statement has two parts "from" and  "where".
Example:
DELETE from dbo.mytabletodelete
WHERE recordno < 15;

This statement basically deletes records based on where clause.
 
::TRUNCATE
This statement deletes all rows from a table. It performs better than delete statement. Truncate resets identity value back to original seed. One good protection to delete all rows from a table is to set foreign keys on this table. Truncate statement does not work if the target table is referenced by a foreign key constraint.
Example:
Truncate Table dbo.mytableallrows;

USE AdventureWorks;

GO
--Copy some table to dummy table for testing
Select * into dbo.truncatetest
from HumanResources.JobCandidate;

SELECT COUNT(*) AS BeforeTruncateCount
FROM dbo.truncatetest;

TRUNCATE TABLE dbo.truncatetest;

SELECT COUNT(*) AS AfterTruncateCount
FROM dbo.truncatetest;

GO::DELETE With A  Join Operation
You may want to delete filtered records  from the join operation. You can join multiple tables and check columns from those tables.
 
DELETE FROM T1
from dbo.atable as T1
 join dbo.btable as T2
 on T1.rowid = T2.rowid
where T1.afield = "something" and T2.anotherfield = "another"

Wow, we delete records from table T1 based on two conditions. You can write complex queries to filter what to delete.

::Delete with Top option
You can specify how many records to delete. If you want to take top 10 of some ordered list, you can do that.
 USE AdventureWorks;

DELETE TOP (2) PERCENT
FROM Production.ProductInventory;

::SQL UPDATE Statement
It allows you to update a subset from a table. If we start with the simple example:

UPDATE dbo.Products
  Set price = price * 1.1
WHERE Color = "blue"

Update happens in one call, so you can easily assign one column to anotherr column.

Update Table1
 Set col1 = col1 + 5, col2 = col1 + 3;

if Col1 is 10 and Col2 is 15 before the assignment, their values will be 15 and 13 after the assignment.

You can Update rows based on a join. This is similar to DELETE operation.

::UPdate based on a Join

UPDATE PR

Set price = price * 1.1
from dbo.Products as PR
  join dbo.Orders as O
  on PR.productid = O.productid

WHERE PR.Color = "blue" and O.orderstatus = "incomplete"
 
::Here, we use Orders table to find records with specific orderstatus for an update operation.

::OUTPUT Clause in Update
--if you are curious to see the column values before the update and after the update, you can use OUTPUT clause to return them

UPDATE dbo.OrderDetails
    set priority = priority +1
OUTPUT
    inserted.productid, deleted.priority as oldp,
    inserted.priority as newp
where  productid > 91;

------The end---------Next---> MERGe operations--->