Category: SQL Server

  • How to get day of the week from a datetime in SQL Server

    The day of the week can be retrieved in SQL Server by using the DatePart function. The value returned by function is between 1 (Sunday) and 7 (Saturday). To convert this to a string representing the day of the week, use a CASE statement.

    Method 1:
    Create function running following script:

    CREATE FUNCTION dbo.udf_DayOfWeek(@dtDate DATETIME)
    RETURNS VARCHAR(10)
    AS
    BEGIN
    DECLARE @rtDayofWeek VARCHAR(10)
    SELECT @rtDayofWeek = CASE DATEPART(weekday,@dtDate)
    WHEN 1 THEN 'Sunday'
    WHEN 2 THEN 'Monday'
    WHEN 3 THEN 'Tuesday'
    WHEN 4 THEN 'Wednesday'
    WHEN 5 THEN 'Thursday'
    WHEN 6 THEN 'Friday'
    WHEN 7 THEN 'Saturday'
    END
    RETURN (@rtDayofWeek)
    END
    GO
    

    Call this function like this:
    SELECT dbo.udf_DayOfWeek(GETDATE()) AS DayOfWeek
    ResultSet:
    DayOfWeek
    ———-
    Monday

    Method 2:

    SELECT DATENAME(dw, GETDATE())

  • Clear all your SQL Server database with just 6 lines of T-SQL

    This is a SQL Script that Cleans your Database Records & resets Identity Columns, and it is all in 6 lines!

    /*Disable Constraints & Triggers*/
    exec sp_MSforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
    exec sp_MSforeachtable 'ALTER TABLE ? DISABLE TRIGGER ALL'
    
    /*Perform delete operation on all table for cleanup*/
    exec sp_MSforeachtable 'DELETE ?'
    
    /*Enable Constraints & Triggers again*/
    exec sp_MSforeachtable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
    exec sp_MSforeachtable 'ALTER TABLE ? ENABLE TRIGGER ALL'
    
    /*Reset Identity on tables with identity column*/
    exec sp_MSforeachtable 'IF OBJECTPROPERTY(OBJECT_ID(''?''), ''TableHasIdentity'') = 1 BEGIN DBCC CHECKIDENT (''?'',RESEED,0) END'
  • Find the tables that use the most disk space in SQL SERVER

    Simply start a new query window for the database and use the statement below:

    SELECT object_name(i.object_id) as objectName,
    i.[name] as indexName,
    sum(a.total_pages) as totalPages,
    sum(a.used_pages) as usedPages,
    sum(a.data_pages) as dataPages,
    (sum(a.total_pages) * 8 ) / 1024 as totalSpaceMB,
    (sum(a.used_pages) * 8 ) / 1024 as usedSpaceMB,
    (sum(a.data_pages) * 8 ) / 1024 as dataSpaceMB
    FROM sys.indexes i
    INNER JOIN sys.partitions p
    ON i.object_id = p.object_id
    AND i.index_id = p.index_id
    INNER JOIN sys.allocation_units a
    ON p.partition_id = a.container_id
    GROUP BY i.object_id, i.index_id, i.[name]
    ORDER BY sum(a.total_pages) DESC, object_name(i.object_id)
    GO