Saturday 5 October 2013

Encrypt Decrypt Password in SQL 2005



 BEGIN TRAN

-- Create Master Key

CREATE MASTER KEY ENCRYPTION BY
    PASSWORD ='man@123'


-- Create Certificate

CREATE CERTIFICATE TEST_Certificate
    WITH SUBJECT='Maneesh'


-- Create Symmetric Key

CREATE SYMMETRIC KEY TEST_SYMKEY
    WITH ALGORITHM = TRIPLE_DES
    ENCRYPTION BY CERTIFICATE TEST_Certificate


-- Inserting records into the table

    OPEN SYMMETRIC KEY TEST_SYMKEY
       DECRYPTION BY CERTIFICATE TEST_Certificate;


    INSERT INTO TestTable
    ([NAME], PASSWORD)
    VALUES
    ('amit', EncryptByKey(Key_GUID('TEST_SYMKEY'), 'pass@123'))


    CLOSE SYMMETRIC KEY TEST_SYMKEY


-- Drop or Close Master Key

    CLOSE MASTER KEY -- FOR CLOSE
    DROP MASTER KEY -- FOR DROP

-- Getting the output again

    OPEN SYMMETRIC KEY TEST_SYMKEY DECRYPTION
    BY CERTIFICATE TEST_Certificate

    SELECT CONVERT(VARCHAR(50),DecryptByKey(Password)) AS DecryptSecondCol
    FROM TestTable




Reference: Govind Badkur(http://sqlserver20.blogspot.com)

Tuesday 21 May 2013

Recursive Queries using Common Table Expressions (CTE)

       Sometimes we have data in a Hierarchical format, and we are to perform some Insert/Update/Delete operation over there. In this situation if the DataBase Server is SQL Server 2000 or lower version, then the task becomes bit complex and need to apply the logic with the help of views, cursors, temp tables or any other object.

        But, if the Database Server is SQL Server 2005 or later version, then the task becomes easier and can implement the Common Table Expressions (CTE).

        Here is an example to elaborate the concept. Let's say we have table UserDetails as below :


UserIDCityNameParentID
U001MumbaiU001
U002BhopalU002
U003DelhiU003
U004BhopalU002
U005MumbaiU001
U006DelhiU003
U007MumbaiU001
U008DelhiU003
U009BhopalU002
U010MumbaiU001
U011DelhiU003
U012MumbaiU001


    Now from the above table we like to get all the users which come under the hierarchy of user having UserID as "U001".

  To get the above result, we will apply the CTE with below code :


;WITH CTE
AS
(
      SELECT * FROM UserDetails 
      WHERE UserID = 'U001'
      UNION ALL
       
      SELECT  MS.*
      FROM  UserDetails MS
              ON MP.UserID = MS.ParentID
              INNER JOIN CTE MP
)
SELECT * FROM CTE
ORDER BY UserID



 Executing the above code, we will get the below ouput :


UserIDCityNameParentID
U001MumbaiU001
U005MumbaiU001
U007MumbaiU005
U010MumbaiU007
U012MumbaiU005




 Reference: Govind Badkur(http://sqlserver20.blogspot.com)