December 31, 2011

Check database exists or not in SQL

T-SQL IF EXISTS( SELECT * FROM sys.databases WHERE name = 'DBName' ) BEGIN       PRINT 'Database Exists.' END ELS...

T-SQL

IF EXISTS(SELECT * FROM sys.databases WHERE name = 'DBName')
BEGIN
      PRINT 'Database Exists.'
END
ELSE
BEGIN

      PRINT 'Database does not exist.'
END

That’s It.
Enjoy Learning.

List all stored procedures modified or created in last N days

Created in last 15 Days SELECT ROUTINE_NAME AS 'Stored Procedure' , ROUTINE_DEFINITION AS 'Stored Procedure Text FROM INFORM...

Created in last 15 Days

SELECT
ROUTINE_NAMEAS 'Stored Procedure'
,ROUTINE_DEFINITION AS 'Stored Procedure Text
FROM INFORMATION_SCHEMA.ROUTINES
WHERE
CREATED >= GETDATE()-15
AND
ROUTINE_TYPE='PROCEDURE'
ORDER BY ROUTINE_NAMEASC

Modified in last 15 Days

SELECT ROUTINE_NAMEAS 'Stored Procedure'
,ROUTINE_DEFINITION AS 'Stored Procedure Text
FROM INFORMATION_SCHEMA.ROUTINES
WHERE
LAST_ALTERED >= GETDATE()-30
AND
ROUTINE_TYPE='PROCEDURE'
ORDER BY ROUTINE_NAMEASC


That’s It.
Enjoy Learning.

Fetch records from remote server without linked server

We can use OPENROWSET for this case if we have credential details of remote SQL Server. T-SQL SELECT      * FROM OPENROWSET ( 'SQLNCLI...

We can use OPENROWSET for this case if we have credential details of remote SQL Server.

T-SQL

SELECT     *
FROM
OPENROWSET('SQLNCLI',
'DRIVER={SQL Server};SERVER=ServerName;UID=sa;
PWD=XXXX;database=DBName;',
'SELECT * FROM dbo.TableName')

That’s It.
Enjoy Learning.

Add serial number in select result SQL

We have following select result records. And my desired output should be: T-SQL DECLARE @Table Table ( SQLForum VARCHAR ( 100 )) INSERT...

We have following select result records.

image

And my desired output should be:

image

T-SQL

DECLARE @Table Table
(SQLForum VARCHAR(100))

INSERT INTO @Table
SELECT 'MSDN' UNION ALL
SELECT 'StackOverFlow' UNION ALL
SELECT 'SQLServerCentral' UNION ALL
SELECT 'SQLTeam'

SELECT ROW_NUMBER()OVER(ORDER BY(SELECT 1))AS 'SRNo',* FROM @Table


That’s It.
Enjoy Learning.

December 30, 2011

Repeat rows in SQL

I have following records in my table. And expected output should be: T-SQL DECLARE @Table Table ( Name VARCHAR ( 100 )) INSERT INTO @...

I have following records in my table.

image

And expected output should be:

image

T-SQL

DECLARE @Table Table
(Name VARCHAR(100))

INSERT INTO @Table
SELECT 'Jim' UNION ALL
SELECT 'Sam' UNION ALL
SELECT 'Pit' UNION ALL
SELECT 'Mac'

SELECT Name FROM @Table
CROSS JOIN
(

SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3
) AS TTable(Col)

That’s It.
Enjoy Learning.

December 28, 2011

Find previous month data in SQL

We have following records in our table. Now we need to fetch previous month data only. Means output should be: T-SQL DECLARE @TablePM TAB...

We have following records in our table.

image

Now we need to fetch previous month data only.
Means output should be:

image

T-SQL

DECLARE @TablePM TABLE
([DATE] DATETIME)

INSERT INTO @TablePM
SELECT '2011-12-28 11:26:03.653' UNION ALL
SELECT '2011-12-18 11:26:03.653' UNION ALL
SELECT '2011-12-18 11:26:03.653' UNION ALL
SELECT '2011-12-17 11:26:03.653' UNION ALL
SELECT '2011-11-28 11:26:03.653' UNION ALL
SELECT '2011-11-30 11:26:03.653' UNION ALL
SELECT '2011-11-08 11:26:03.653' UNION ALL
SELECT '2011-11-27 11:26:03.653' UNION ALL
SELECT '2011-11-21 11:26:03.653' UNION ALL
SELECT '2011-11-01 11:26:03.653' UNION ALL
SELECT '2012-11-28 11:26:03.653' UNION ALL
SELECT '2012-12-28 11:26:03.653'

SELECT * FROM @TablePM
WHERE
DATEPART(M, [DATE]) = DATEPART(M, DATEADD(M, -1, GETDATE()))
AND

DATEPART(YEAR, [DATE]) = DATEPART(YEAR, DATEADD(M, -1, GETDATE()))

That’s It.
Enjoy Learning.

December 17, 2011

How to disable cut copy paste in a textbox

Sometimes it is very necessary to disable cut,copy & paste in a textbox. We can easily do it in ASP.Net. < asp : TextBox ID = "...

Sometimes it is very necessary to disable cut,copy & paste in a textbox.
We can easily do it in ASP.Net.

<asp:TextBox ID="txtDisableCutCopyPaste" runat="server" oncopy="return false" 
     onpaste="return false" oncut="return false">
</asp:TextBox>

It’s very handy technique.

That’s It.
Enjoy Learning.

Template Explorer In SQL Server

We can see all types of syntax in Template Explorer. View ==> Template Explorer   That’s It Enjoy Learning.

We can see all types of syntax in Template Explorer.
View ==> Template Explorer
 

That’s It
Enjoy Learning.

Replace paragraph with new line in MS-Word

We can replace paragraph mark with new line in MS-Word. Sometimes it makes my writing very easy for some forum. Replace ^p with ^l. That’s ...

We can replace paragraph mark with new line in MS-Word.
Sometimes it makes my writing very easy for some forum.

Replace ^p with ^l.

That’s It
Enjoy Learning.

December 7, 2011

IS SQL Server 32 bit or 64 bit

Using above statement we can find SQL server version.If it is 32 bit it will bring edition name only otherwise it will 64 bit added with ed...


image

Using above statement we can find SQL server version.If it is 32 bit it will bring edition
name only otherwise it will 64 bit added with edition name in output.

That’s It.
Enjoy Learning.

CASE statement in UPDATE SQL Server

We can use CASE statement with UPDATE command in SQL Server. We have following records in table. Let’s try to update tables with case state...

We can use CASE statement with UPDATE command in SQL Server.
We have following records in table.

image

Let’s try to update tables with case statement.

T-SQL:

DECLARE @TableUpdateCase TABLE
(Department VARCHAR(30),SalaryPercent INT)
INSERT INTO @TableUpdateCase
SELECT 'IT',60 UNION ALL
SELECT 'HR',20 UNION ALL
SELECT 'TECH',40 UNION ALL
SELECT 'ACCOUNT',30 UNION ALL
SELECT 'ADMIN',40 UNION ALL
SELECT 'SALES',80 
UPDATE  @TableUpdateCase
SET
SalaryPercent = SalaryPercent + 
		CASE 
		WHEN Department = 'IT' THEN 5
		WHEN Department = 'HR' THEN 4
		WHEN Department = 'TECH' THEN 9
		WHEN Department = 'ACCOUNT' THEN 7	
		WHEN Department = 'ADMIN' THEN 9
		WHEN Department = 'SALES' THEN 8		
		END
SELECT * FROM @TableUpdateCase

After UPDATE table status has become:

image

That’s It.
Enjoy Learning.

December 6, 2011

Export query results to Notepad

We have bcp utility in SQL Server we can easily write query results to notepad file. T-SQL EXEC xp_cmdshell ' bcp "SELECT * FROM ...

We have bcp utility in SQL Server we can easily write query results to notepad file.

T-SQL

EXEC xp_cmdshell 'bcp "SELECT * FROM sys.objects" 
queryout "C:\ExportDataToNotepad.txt" -T -c -t,'

That’s It.
Enjoy Learning.

December 5, 2011

Hierarchical query example in SQL Server

We have following records in our table. We want output should come in this format. This is best example of hierarchical query. Let’s try ...

We have following records in our table.

image

We want output should come in this format.

image

This is best example of hierarchical query.
Let’s try to write it.

T-SQL

CREATE TABLE TableCTE (ID int, ParentID int NULL, Name varchar(128));
INSERT INTO TableCTE VALUES (1, NULL, 'A');
INSERT INTO TableCTE VALUES (2, 1, 'B');
INSERT INTO TableCTE VALUES (3, 2, 'C');
INSERT INTO TableCTE VALUES (4, 3, 'D');
INSERT INTO TableCTE VALUES (5, 4, 'E');
SELECT * FROM TableCTE
WITH Parent AS
(
    SELECT
        ID,
        ParentID,
        Name,
        Name AS Path
    FROM
        TableCTE
    WHERE
        ParentID IS NULL
    UNION ALL
    SELECT
        TH.ID,
        TH.ParentID,
        TH.Name,
        CONVERT(varchar(128), Parent.Path + ',' + TH.Name) AS Path
    FROM
        TableCTE TH
    INNER JOIN
        Parent
    ON
        Parent.ID = TH.ParentID
)
SELECT * FROM Parent

That’s It.
Enjoy Learning.

December 2, 2011

Insert result of stored procedure into temp table SQL Server

How can we insert stored procedure result in a temporary table. CREATE PROC spGetDateList AS BEGIN SELECT GETDATE() AS [ DATE ] U...

How can we insert stored procedure result in a temporary table.
CREATE PROC spGetDateList
AS
BEGIN
    SELECT GETDATE()   AS [DATE]  UNION ALL
    SELECT GETDATE()+1 AS [DATE]  UNION ALL
    SELECT GETDATE()+2 AS [DATE]  UNION ALL
    SELECT GETDATE()+3 AS [DATE]  UNION ALL
    SELECT GETDATE()+4 
    
END
GO
sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO
SELECT * INTO #TempTable FROM 
OPENROWSET('SQLNCLI', 'Server=ServerInstanceName;Trusted_Connection=yes;',
'EXEC Database.Schema.StoredProcedure')

That’s It
Enjoy Learning.
 

December 1, 2011

Find cumulative sum In SQL

How can we find cumulative sum in SQL Server. T-SQL DECLARE @Table TABLE (ID INT ,Amount INT ) INSERT INTO @Table SELECT 1, 200 UNION A...

How can we find cumulative sum in SQL Server.
T-SQL


DECLARE
@Table TABLE
(ID INT,Amount INT)

INSERT INTO @Table
SELECT 1, 200 UNION ALL
SELECT 2,,200 UNION ALL
SELECT 3, 100 UNION ALL
SELECT 4, 350 UNION ALL
SELECT 5, 100

SELECT T1.ID,T1.Amount,SUM(T2.Amount) AS 'Cum Sum'
FROM @Table T1 JOIN @Table T2 ON T2.ID <= T1.ID
GROUP BY T1.ID,T1.Amount

That’s It
Enjoy Learning.

Remove Characters from String in SQL

Here is a function that will remove all characters from string. CREATE FUNCTION [dbo].[RemoveCharacters](@Str VARCHAR (500)) RETURNS VARC...

Here is a function that will remove all characters from string.
CREATE FUNCTION [dbo].[RemoveCharacters](@Str VARCHAR(500))
RETURNS VARCHAR(500)
AS
BEGIN
    WHILE PatIndex('%[^0-9]%', @Str) > 0
    SET @Str = Stuff(@Str, PatIndex('%[^0-9]%', @Str), 1, '')
RETURN @Str 
END
DECLARE @Str VARCHAR(100)
SET @Str = 'A1X2Y3'
SELECT [dbo].RemoveCharacters(@Str)

That’s It.
Enjoy Learning.
 

Get current week data in SQL Server

Select current entries from table. T-SQL DECLARE @TableX TABLE ([ Date ] DATETIME ) INSERT INTO @TableX SELECT ' 2011-11-28 ' UN...

Select current entries from table.
T-SQL
DECLARE @TableX TABLE
([Date] DATETIME)
INSERT INTO @TableX
SELECT '2011-11-28' UNION ALL
SELECT '2011-11-25' UNION ALL
SELECT '2011-11-27' UNION ALL
SELECT '2011-11-29' UNION ALL
SELECT '2011-11-30' UNION ALL
SELECT '2011-11-11' UNION ALL
SELECT '2011-11-21' UNION ALL
SELECT '2011-12-01'
SELECT * FROM @TableX
WHERE
DATE BETWEEN 
DATEADD(DD, 1 - DATEPART(DW, GETDATE()),GETDATE())
AND
DATEADD(DD, 1 - DATEPART(DW, GETDATE()),GETDATE())+7

That’s It.
Enjoy Learning.