Showing posts with label T-SQL. Show all posts
Showing posts with label T-SQL. Show all posts

Wednesday, 13 July 2016

Rename Column Name in SQL Server 2005, 2008, 2012

In SQL Server 2005, 2008, 2012 to rename a column in a table we can call an SP  sp_RENAME as below :

    

EXEC sp_RENAME 'TableName.OldColumnName' , 'NewColumnName', 'COLUMN'

    
 


Alternately, open the table in Object Explorer and then right click on the desired column and select RENAME. Give a new column name here.



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

Friday, 6 May 2016

Find Stored Procedures containing a text

Somewhere or Sometimes, we need to Access/Update/Delete all the Stored Procedures which contain some specific text in the name of DataObjects (like SP or Function) or in the definition of DataObjects. In such cases, first we need to get the list of all DataObjects containing the text. Now to get the list of such DataObjects which contain the text in their names, we will write the following query :

 

--#####################################################################################

SELECT      ROUTINE_CATALOG, ROUTINE_NAME, ROUTINE_DEFINITION 
FROM        INFORMATION_SCHEMA.ROUTINES 
WHERE       ROUTINE_NAME LIKE '%NAME%'
            AND ROUTINE_TYPE ='PROCEDURE'
ORDER BY	CREATED

--#####################################################################################
    
 


Here in where clause "ROUTINE_TYPE ='PROCEDURE'" is given to search for Stored Procedures only. Now if you like to search a text 'NAME' in the definition of the DataObjects, then the query will be a bit changed as :

  

--#####################################################################################

SELECT      ROUTINE_CATALOG, ROUTINE_NAME, ROUTINE_DEFINITION 
FROM        INFORMATION_SCHEMA.ROUTINES 
WHERE       ROUTINE_DEFINITION LIKE '%ghost%'
            AND ROUTINE_TYPE ='PROCEDURE'
ORDER BY	CREATED'

--#####################################################################################
    
 


Some other ways to find the same output is as below :
  

--#####################################################################################

SELECT	OBJECT_NAME(OBJECT_ID) AS ObjectName, Definition
FROM	SYS.SQL_MODULES
WHERE	OBJECTPROPERTY(OBJECT_ID, 'IsProcedure') = 1
		AND DEFINITION LIKE '%ghost%'
ORDER BY OBJECT_ID

SELECT	OBJECT_NAME(ID) AS ObjectName, Text
FROM	SYSCOMMENTS 
WHERE	[TEXT] LIKE '%ghost%' 
		AND OBJECTPROPERTY(ID, 'IsProcedure') = 1 
ORDER BY ID

--#####################################################################################
    
 

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

Numeric Characters Only in SQL Server 2005, 2008, 2012

In SQL Server 2005, 2008, 2012 if you wish to find all the rows with a particular field having Numeric values only then give a simple check as below :


SELECT * FROM CustomerDetails (NOLOCK)
WHERE MobileNo NOT LIKE '%[^0-9]%'



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

Remove Tab, Newline Character From Data In SQL Server


In SQL Server 2005, 2008, 2012, If you are facing some inconsistency with data while selecting and other operations and find that this is due to tab or newline characters, then just replace them with blank.


REPLACE(REPLACE(REPLACE(MyField, CHAR(10), ''), CHAR(13), ''), CHAR(9), '')



CHAR(9) - Tab
CHAR(10) – LineFeed
Char(13) - CarriageReturn

CR ("carrige return") is ASCII code 13, and means "go back to the beginning of the line". It tells the Teletype machine to bring the print head to the left.

LF ("Line Feed") is ASCII code 10, and tells the printer to move the paper up 1 line.


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

Email Validation in SQL In SQL Server 2005, 2008, 2012

In SQL Server 2005, 2008, 2012 for email validation I found that either you can write a plane query as below :


SELECT * FROM people WHERE email NOT LIKE '%_@__%.__%'



Or can write a function as below : "


CREATE FUNCTION dbo.ValidateEmail(@EMAIL VARCHAR(100))

RETURNS BIT AS
BEGIN     
  DECLARE @bitRetVal AS BIT
  IF (@EMAIL <> '' AND @EMAIL NOT LIKE '_%@__%.__%')
     SET @bitRetVal = 0  -- Invalid
  ELSE 
    SET @bitRetVal = 1   -- Valid
  RETURN @bitRetVal
END



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)

Sunday, 21 October 2012

SP Slow in Application Fast in SSMS

 In SQL Server 2005, 2008, 2012,  SP Slow in Application Fast in SSMS: Once I had this issue with my job running in the morning 6:00 AM, which was processing some 20 millions records daily within 10 mins. Initially everything was ok, but some days later, I found that the job was running for over 5 hrs. and was creating issues to all other Online Applications.

I googled and found that it can be removed by setting the arithabort property ON.

To set the arithabort property ON, Just give a set command as below :

 


CREATE PROC usp_ProcedureName
       @UserID    VARCHAR(100)
      ,@FromDate  DATETIME
      ,@ToDate    DATETIME
AS
BEGIN
SET NOCOUNT ON
SET ARITHABORT ON
      SELECT  UserID, UserName,..
      FROM  UserDetails (NOLOCK)
      WHERE TransDate BETWEEN @FromDate AND @ToDate
           
SET ARITHABORT OFF --- If you want to keep it off.
SET NOCOUNT OFF
END



   But, if you are a Developer and not a DBA and don't want to interfere with the SERVER properties; then Make a Variable Sniffing, that means take the parameters value into the local variables as below :


CREATE PROC usp_ProcedureName
       @UserID    VARCHAR(100)
      ,@FromDate  DATETIME
      ,@ToDate    DATETIME
AS
BEGIN
SET NOCOUNT ON
      DECALRE @FromDT   DATETIME, @ToDT   DATETIME
      SET @FromDT = @FromDate
      SET @ToDT   = @ToDate
      SELECT  UserID, UserName,..
      FROM  UserDetails (NOLOCK)
      WHERE TransDate BETWEEN @FromDT AND @ToDT
           
SET NOCOUNT OFF
END


and here you are done...


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

Tuesday, 11 September 2012

Non Working Days Between the Two Dates

    In MS SQL, for getting Working Days or Non Working Days between the two Dates, it is always good to maintain a calender table. Though you can find all the Dates falling on 'Saturday' or 'Sunday' by the query script as below:

DECLARE @FromDate DATETIME, @ToDate DATETIME
SET @FromDate = '2012-04-01'
SET @ToDate = '2015-03-31'

;WITH CTE
AS
(
SELECT  CAST(@FromDate AS DATETIME) WorkingDate
        ,DATENAME(DW,@FromDate) DayName
UNION ALL
SELECT  WorkingDate + 1 AS WorkingDate
        ,DATENAME(DW,WorkingDate + 1) DayName
FROM   CTE
WHERE  WorkingDate <= @ToDate
)
SELECT *
FROM   CTE
WHERE  DayName NOT IN ('Saturday','Sunday')
OPTION (MAXRECURSION 0)



     But when you see the actual calender of an Organization, it includes National Holidays, Regional Holidays, some Festival Holidays etc.. So maintaining a calender table is needed. Here is an example, how we can maintain a Calender table:

----- Creating a Calender Table :

CREATE TABLE CalenderTable
(
 DATE                DATETIME
,DayName             VARCHAR(10)
,[Month]             INT
,[Year]              INT
,IsBusinessDay       BIT
,Description  VARCHAR(50)
)

--- Inserting Dates excluding 'Saturday' and 'Sunday':

DECLARE @FromDate    DATETIME, @ToDate    DATETIME
SET @FromDate = '2012-04-01'
SET @ToDate = '2015-03-31'

;WITH CTE
AS
(
SELECT  CAST(@FromDate AS DATETIME) WorkingDate
        ,DATENAME(DW,@FromDate) DayName
        ,MONTH(@FromDate) Months,YEAR(@FromDate) Years
UNION ALL
SELECT  WorkingDate + 1 AS WorkingDate
        ,DATENAME(DW,WorkingDate + 1) DayName
        ,MONTH(WorkingDate + 1) Months,YEAR(WorkingDate + 1) Years
FROM   CTE
WHERE  WorkingDate <= @ToDate
)
INSERT INTO CalenderTable
SELECT CTE.* ,1,'Business Day'
FROM   CTE
WHERE  DayName NOT IN ('Saturday','Sunday')
OPTION (MAXRECURSION 0)

---Inserting Dates falling on 'Saturday' or 'Sunday':

;WITH CTE
AS
(
SELECT  CAST(@FromDate AS DATETIME) WorkingDate
        ,DATENAME(DW,@FromDate) DayName
        ,MONTH(@FromDate) Months,YEAR(@FromDate) Years
UNION ALL
SELECT  WorkingDate + 1 AS WorkingDate
        ,DATENAME(DW,WorkingDate + 1) DayName
       ,MONTH(WorkingDate + 1) Months,YEAR(WorkingDate + 1) Years
FROM   CTE
WHERE  WorkingDate <= @ToDate
)
INSERT INTO CalenderTable
SELECT CTE.* ,0,'WEEK OFF'
FROM   CTE
WHERE  DayName IN ('Saturday','Sunday')
OPTION (MAXRECURSION 0)

--- Updating other Dates which are Declared Holidays:

UPDATE CalenderTable
SET IsBusinessDay = 0
,Description = 'Independence Day'
WHERE DATE = '2012-08-15'
UPDATE CalenderTable
SET IsBusinessDay = 0
,Description = 'Christmas Day'
WHERE DATE = '2012-12-25'
UPDATE CalenderTable
SET IsBusinessDay = 0
,Description = 'Republic Day'
WHERE DATE = '2013-01-26'
UPDATE CalenderTable
SET IsBusinessDay = 0
,Description = 'Mahatma Gandhi Birth Anniversary'
WHERE DATE = '2013-01-26'



Now we can fire any type of query from the Calender Table.
Let's say we want to get all the non working days between '2012-08-10' and '2012-08-20', then we will have :

SELECT DATE
FROM CalenderTable
WHERE DATE BETWEEN '2012-08-10' AND '2012-08-20'
       AND IsBusinessDay = 0
--- Output is :
2012-08-11 00:00:00.000
2012-08-12 00:00:00.000
2012-08-15 00:00:00.000
2012-08-18 00:00:00.000
2012-08-19 00:00:00.000







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

Business Days Between the two Dates

   In MS SQL, for getting Business Days between the two Dates or Working Days between the two Dates, it is always good to maintain a calender table. Though you can find all the week days excluding 'Saturday' and 'Sunday' by the query script as below:

DECLARE @FromDate DATETIME, @ToDate DATETIME
SET @FromDate = '2012-04-01'
SET @ToDate = '2015-03-31'

;WITH CTE
AS
(
SELECT  CAST(@FromDate AS DATETIME) WorkingDate
       ,DATENAME(DW,@FromDate) DayName
UNION ALL
SELECT  WorkingDate + 1 AS WorkingDate
       ,DATENAME(DW,WorkingDate + 1) DayName
FROM   CTE
WHERE  WorkingDate <= @ToDate
)
SELECT *
FROM   CTE
WHERE  DayName NOT IN ('Saturday','Sunday')
OPTION (MAXRECURSION 0)



    But when you see the actual calender of an Organization, it includes National Holidays, Regional Holidays, some Festival Holidays etc.. So maintaining a calender table is needed. Here is an example, how we can maintain a Calender table:

----- Creating a Calender Table :

CREATE TABLE CalenderTable
(
 DATE                DATETIME
,DayName             VARCHAR(10)
,[Month]             INT
,[Year]              INT
,IsBusinessDay       BIT
,Description   VARCHAR(50)
)

--- Inserting Dates excluding 'Saturday' and 'Sunday':

DECLARE @FromDate    DATETIME, @ToDate    DATETIME
SET @FromDate = '2012-04-01'
SET @ToDate = '2015-03-31'

;WITH CTE
AS
(
SELECT  CAST(@FromDate AS DATETIME) WorkingDate
         ,DATENAME(DW,@FromDate) DayName
         ,MONTH(@FromDate) Months,YEAR(@FromDate) Years
UNION ALL
SELECT  WorkingDate + 1 AS WorkingDate
        ,DATENAME(DW,WorkingDate + 1) DayName
        ,MONTH(WorkingDate + 1) Months,YEAR(WorkingDate + 1) Years
FROM   CTE
WHERE  WorkingDate <= @ToDate
)
INSERT INTO CalenderTable
SELECT CTE.* ,1,'Business Day'
FROM   CTE
WHERE  DayName NOT IN ('Saturday','Sunday')
OPTION (MAXRECURSION 0)

---Inserting Dates falling on 'Saturday' or 'Sunday':

;WITH CTE
AS
(
SELECT  CAST(@FromDate AS DATETIME) WorkingDate
        ,DATENAME(DW,@FromDate) DayName
        ,MONTH(@FromDate) Months,YEAR(@FromDate) Years
UNION ALL
SELECT  WorkingDate + 1 AS WorkingDate
       ,DATENAME(DW,WorkingDate + 1) DayName
       ,MONTH(WorkingDate + 1) Months,YEAR(WorkingDate + 1) Years
FROM   CTE
WHERE  WorkingDate <= @ToDate
)
INSERT INTO CalenderTable
SELECT CTE.* ,0,'WEEK OFF'
FROM   CTE
WHERE  DayName IN ('Saturday','Sunday')
OPTION (MAXRECURSION 0)

--- Updating other Dates which are Declared Holidays:

UPDATE CalenderTable
SET IsBusinessDay = 0
,Description = 'Independence Day'
WHERE DATE = '2012-08-15'
UPDATE CalenderTable
SET IsBusinessDay = 0
,Description = 'Christmas Day'
WHERE DATE = '2012-12-25'
UPDATE CalenderTable
SET IsBusinessDay = 0
,Description = 'Republic Day'
WHERE DATE = '2013-01-26'
UPDATE CalenderTable
SET IsBusinessDay = 0
,Description = 'Mahatma Gandhi Birth Anniversary'
WHERE DATE = '2013-01-26'



Now we can fire any type of query from the Calender Table.
Let's say we want to get all the working days between '2012-08-10' and '2012-08-20', then we will have :

SELECT DATE
FROM CalenderTable
WHERE DATE BETWEEN '2012-08-10' AND '2012-08-20'
       AND IsBusinessDay = 1
--- Output is :
2012-08-10 00:00:00.000
2012-08-13 00:00:00.000
2012-08-14 00:00:00.000
2012-08-16 00:00:00.000
2012-08-17 00:00:00.000
2012-08-20 00:00:00.000







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