Wednesday, January 20, 2016

suddenly my SQL Server DataBase turn in to restoring mode




suddenly my SQL Server  DataBase turn in to restoring mode, reason was it is executing in
transactions and creating large log files and there was less space in server so limbo condition was created. I restated the SQL Service and it convert db in restoring mode.
to make in normal I executed follwoing commands.
USE master;
GO
ALTER DATABASE M11272015BACKUP 
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;
GO
ALTER DATABASE M11272015BACKUP
SET READ_ONLY;
GO
ALTER DATABASE M11272015BACKUP 
SET MULTI_USER;
GO
ALTER DATABASE M11272015BACKUP
SET READ_WRITE WITH NO_WAIT
GO

Note: If it is still in restore mode use
RESTORE DATABASE M11272015BACKUP WITH RECOVERY


To know table name where used in database

DECLARE @TableName varchar(100)
SET @TableName = 'Users'
SELECT
SourceObject = OBJECT_NAME(sed.referencing_id),
ReferencedDB = ISNULL(sre.referenced_database_name, DB_NAME()),
ReferencedObject = sre.referenced_entity_name,
ReferencedColumnID = sre.referenced_minor_id,
ReferencedColumn = sre.referenced_minor_name
FROM sys.sql_expression_dependencies sed
CROSS APPLY sys.dm_sql_referenced_entities(OBJECT_SCHEMA_NAME(sed.referencing_id)
+ '.' + OBJECT_NAME(sed.referencing_id), 'OBJECT') sre
WHERE sed.referenced_entity_name = @TableName
AND sre.referenced_entity_name = @TableName And sre.referenced_minor_name is not null

Thursday, January 7, 2016

Get the numeric from string in SQL

declare @st varchar(50) ='Mahesh999666777555'

select PatIndex('%[0-9]%',@st)

select substring(@st,PATINDEX('%[0-9]%', @st),len(@st)) GetNumber

Sunday, January 3, 2016

FiscalQuarter + YearQuarter

ALTER FUNCTION [dbo].[GetFiscalQuarters] ( @Asofpdate    DATETIME )
RETURNS varchar(10)
BEGIN

    DECLARE @vOutputDate        varchar(10)

    SET @vOutputDate =  Convert(varchar(max),
(case when DATEPART(M,@Asofpdate) between 5 and 7 then 1 when DATEPART(M,@Asofpdate) between 8 and 10 then 2
when DATEPART(M,@Asofpdate) between 11 and 1 then 3 when DATEPART(M,@Asofpdate) between 2 and 4 then 4
end) ) + CONVERT(varchar(max), Year(@Asofpdate))
   RETURN @vOutputDate

END


ALTER FUNCTION [dbo].[GetYearQuarters] ( @Asofpdate    DATETIME )
RETURNS varchar(10)
BEGIN

    DECLARE @vOutputDate        varchar(10)

    SET @vOutputDate =  Convert(varchar,DATEPART(QUARTER,@Asofpdate)) + CONVERT(varchar, Year(@Asofpdate))
   RETURN @vOutputDate

END

Saturday, January 2, 2016

Good way to format date in SQL server

DECLARE @d DATETIME = GETDATE();
SELECT FORMAT( @d, 'MMMM dd, yyyy', 'en-US' ) AS 'DateTime Result'