Friday, January 23, 2015

SQL Puzzle

 My friend came to me and can you find this word 'S L U N O I O T'. I said 'SOLUTION'.
Then I thought why can't I create a script which will jigjag a input word.

Of course you may do so many other ways.. I have developed like below. If you want to use this for longer strings please change the string length appropriately...


SET NOCOUNT ON
GO
Declare @str VARCHAR(20) = 'SOLUTION' -- You can pass your own word here
DECLARE @val CHAR(1)

DECLARE @valstr VARCHAR(20)
DECLARE @len INT = LEN(@str)
Declare @mytab Table (ID INT IDENTITY,Value char(1),OrderID INT)
DECLARE @i int =1
    WHILE (@len >= @i)
    BEGIN
        SET @val = SUBSTRING(@str,@i,1)
        INSERT INTO @mytab VALUES (@val,rand()*10)
        SET @valstr = SUBSTRING(@str,@i,@len)
        --SET @len = Len(@valstr)
        SET @i = @i +1
    END

SELECT *, row_number() OVER (ORDER BY orderID) RowID into #temp from @mytab


DECLARE @Names VARCHAR(8000)
SELECT @Names = COALESCE(@Names + ', ', '') + value
FROM #temp
 SELECT replace(@names,',','') As WhatIsThisWord
 drop table #temp

Note: Please acknowledge.

Monday, January 5, 2015

Database Snapshot

                                                --Database Snapshot
A database snapshot is a read-only, static view of a SQL Server database. A database snapshot always resides on the same server instance as its source database.


USE master
GO
-- Drop database snapshot if it already exists
IF  EXISTS (
         SELECT name
         FROM sys.databases
         WHERE name = 'MYDB_snapshot'

                   )
DROP DATABASE MYDB_snapshot
GO
-- Create the database snapshot
CREATE DATABASE MYDB_snapshot ON
( NAME = MYDB , -- FileName(Data)
FILENAME =
'C:\PYamani\SQL_Archives\MYDB_snapshot.ss' )
AS SNAPSHOT OF NJSBCL;
GO


-- Dropping the SnapShort database

DROP DATABASE NJSBCL_snapshot1


Notes:

  • The source database must be in Online.
  • To create a database snapshot on a mirror database, the database must be in the SYNCHRONIZED mirroring state.
  • All recovery models support database snapshots.
  • You cannot Drop a database,Detached or restored which holds the at least one Snapshot.
  • Files cannot be dropped from the source database or from any snapshots.
  • You cannot take a backup for the snapshot database.
  • You can have 'N' number of snapshots on a single database, It is depends on the disc space.
    Each database snapshot persists until it is explicitly dropped by the database owner.

-- Testing snapshot by creating new tables
    Once you create a snapshot, you can create a table on source/base database. You can refresh the snapshot tables now to see the new table.
        Create table TestTable (Sno INT)
        Drop table TestTable