Clean Double Quoted Text to Another Table


   create table testtablewithOneColumn (col0 varchar(4000))
Insert into testtablewithOneColumn values('"Some data        ","3800&","827","         ","         ","       ","51345","R","S","          10.00006" ')
,('"         ","3800","827","         ","         ","       ","51345","R","S","          10.00008" ')
,('"row3         ","3800","827","         ","         ","       ","51345","R","S","          10.00009" ')

CREATE TABLE testtablewithTargetColumns (
SalaryCode VARCHAR(50)
,SalaryID VARCHAR(50)
,Department VARCHAR(50)
,Region VARCHAR(50)
,Area VARCHAR(50)
,theMisingCol VARCHAR(50)
,TypeCode VARCHAR(50)
,ShortCode VARCHAR(50)
,ManagerCode VARCHAR(50)
,Units VARCHAR(50)) 

set @cmd1 = 'BCP [mydb1].[dbo].testtablewithOneColumn OUT  "C:\temp\myTableData.txt" -c -r \"\n  -T -S'+ @@servername
exec master..xp_cmdshell @cmd1, no_output 
-- Export to a text file

BULK INSERT  mydb1.[dbo].testtablewithTargetColumns
  FROM 'C:\temp\myTableData.txt'
        FIELDTERMINATOR ='","',
        ROWTERMINATOR ='" "\n',

---remove the first  double quote
Update  mydb1.[dbo].testtablewithTargetColumns
SalaryCode=Replace(SalaryCode,'"', '')  

  --Check the target table
select SalaryCode
	 , SalaryID, Department, Region, Area, theMisingCol, TypeCode, ShortCode, ManagerCode, Units
 from  mydb1.[dbo].testtablewithTargetColumns

 --clean up
 drop table testtablewithOneColumn,testtablewithTargetColumns


Format Date with st,nd,rd or th and a way to remove them with TSQL


create table test (dt datetime)
--===== Create number table on-the-fly
;WITH Num1 (n) AS (
SELECT 1 as n
FROM Num1 Where n<101),
Num2 (n) AS (SELECT 1 FROM Num1 AS X, Num1 AS Y),

Insert into test (dt) 

Select dateadd(day, n, dt)  dt from (
select getdate() as dt )t Cross apply (select n from nums ) d(n)

-- select * from test

SELECT 'Date formated with st,nd,rd or th ----- ' col1,  DATENAME(month, dt) + ' ' + DATENAME(day, dt) + 
		WHEN DATENAME(day, dt) IN ('1', '21', '31') THEN 'st'
		WHEN DATENAME(day, dt) IN ('2', '22') THEN 'nd'
		WHEN DATENAME(day, dt) IN ('3', '23') THEN 'rd'
		ELSE 'th'
	+ ' ' + DATENAME(Year, dt)   dtFormatedwith_st_nd_rd_th

Into testdtFormatedwith_st_nd_rd_th
From test

--Select * from testdtFormatedwith_st_nd_rd_th

--Convert back to date
 Select  dtFormatedwith_st_nd_rd_th
 , try_Convert(datetime, Replace(Replace(Replace(Replace(dtFormatedwith_st_nd_rd_th,'1st','1'),'nd',''),'rd',''),'th','') ) dt_2
 --,Convert(datetime, Replace(Replace(Replace(Replace(dtFormatedwith_st_nd_rd_th,'1st','1'),'nd',''),'rd',''),'th','') )
 from testdtFormatedwith_st_nd_rd_th

drop table testdtFormatedwith_st_nd_rd_th
drop table test

Mark Last Five Fiscal Years in a Column


CREATE TABLE dbo.financial_years (id int identity(1,1),	start_of_fin_year date,	end_of_fin_year date);

-- Load sample financial_years from 2008 to 2017
	INSERT INTO dbo.financial_years (start_of_fin_year, end_of_fin_year)
	SELECT	DATEADD(YEAR, -1*n , start_of_fin_year),	DATEADD(YEAR, -1*n , end_of_fin_year)
	from (select '2018-04-01' as start_of_fin_year, '2019-03-31' as end_of_fin_year) t
			Cross apply(values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) d(n)
--get beginningofCurrentFY
;with mycte as (
Case when Month(getdate())>3 then Dateadd(month,3,dateadd(Year, datediff(year,0,getdate()),0))
else Dateadd(month,3,dateadd(Year, datediff(year,0,getdate())-1,0)) end beginningofCurrentFY

-- declare @today date ='2016-4-2'
-- ;with mycte as (select
--Case when Month( @today)>3 then Dateadd(month,3,dateadd(Year, datediff(year,0, @today),0))
--else Dateadd(month,3,dateadd(Year, datediff(year,0, @today)-1,0)) end beginningofCurrentFY)

select start_of_fin_year, end_of_fin_year ,
case when  start_of_fin_year<=beginningofCurrentFY
and  start_of_fin_year< (dateadd(Year,-5,beginningofCurrentFY) )
then 'Yes' else 'No' End    from financial_years
cross apply (Select beginningofCurrentFY from mycte) d(beginningofCurrentFY)

drop table financial_years


Sort Order with Multiple Levels Using T-SQL


  CREATE TABLE [dbo].[test](
	[Lev1] [char](1) NULL,
	[LeV2] [char](2) NULL,
	[Lev3] [int] NULL,
	[Price] [int] NULL

INSERT [dbo].[test] ([Lev1], [LeV2], [Lev3], [Price]) VALUES  (N'A', NULL, NULL, 80)
,(N'A', N'1 ', NULL, 30)
,(N'A', N'1 ', 1234, 10)
,(N'A', N'1 ', 1235, 5)
,(N'A', N'1 ', 1236, 15)
,(N'A', N'2 ', NULL, 50)
,(N'A', N'2 ', 1237, 20)
,(N'A', N'2 ', 1238, 5)
,(N'A', N'2 ', 1239, 25)
,(N'B', NULL, NULL, 90)
,(N'B', N'1 ', NULL, 30)
,(N'B', N'1 ', 1240, 30)
,(N'B', N'2 ', NULL, 60)
,(N'B', N'2 ', 1242, 10)
,(N'B', N'2 ', 1243, 50)

;with mycte as (
SELECT[Lev1], [LeV2], [Lev3],[Price]
	  ,dense_rank() Over( Order by [Lev1] desc) rn1
	  ,dense_rank() Over( Order by [Lev1] desc,Case when Lev2 is null then 9999 else Lev2 end  desc) rn2
	  ,dense_rank() Over( Order by [Lev1] desc,Lev2 desc,Case when Lev3 is null then 9999 else Lev3+Price end desc) rn3
  FROM  [dbo].[test]

SELECT [Lev1], [LeV2], [Lev3],[Price]
--, rn1, rn2, rn3
FROM   mycte
ORDER  BY rn1, rn2, rn3 

 Lev1	LeV2	Lev3	Price
B	2 	NULL	60
B	2 	1243	50
B	2 	1242	10
B	1 	NULL	30
B	1 	1240	30
A	2 	NULL	50
A	2 	1239	25
A	2 	1237	20
A	2 	1238	5
A	1 	NULL	30
A	1 	1236	15
A	1 	1234	10
A	1 	1235	5

--Another solution
select Lev1,Lev2, Lev3, Price from test
Order by Cast(Lev1 as binary(8)) desc
, Cast(Case when Lev2 is null then 9999 else Lev2 end as binary(8)) desc
, Cast(Case when Lev3 is null then 9999 else Lev3 + Price end as binary(8)) desc

drop table test

Read Last 7 Days Erro Log with xp_ReadErrorLog

declare @dt1 datetime=getdate()-7
declare @dt2 datetime=getdate()

EXEC xp_ReadErrorLog 0, 1, N’error’, N”,@dt1,@dt2

—-Or Failed Login
–EXEC xp_ReadErrorLog 0, 1, “Failed”, “Login”,@dt1,@dt2

—-****** the syntax with double quotes “Failed”

(Script above was  on SQL Server 2014)

System Function msdb.dbo.agent_datetimeMSDB.dbo.sysjobhistory Table and Run_duration Column

In the msdb.dbo.sysjobhistory table, the run_duration column is INT type and stored as (H)HHMMSS format from right to left.
If HH is under 24 hours, we can get the during in time format HH:MM:SS by using a system function. For example:
select msdb.dbo.agent_datetime(19000101, 231353) will return 23:13:53 9 23 hours 13 minutes and 53 seconds.

In very long running job, if the hours go over 24 hours, all the numbers in HHH positions are whole number of hours.

We need to tweak a little to make it work:

       msdb.dbo.Agent_datetime(run_date, run_time) [Run_Datetime] 
,Case when run_duration&gt;24*10000 then 
Cast(run_duration%240000/10000 as varchar(3)) +' (day) '
+ Cast(run_duration/240000 as varchar(2))  
+':' + LefT(Right(Cast(run_duration as varchar(8)),4),2)
+':'+ Right(Cast(run_duration as varchar(8)),2) +''
Format(msdb.dbo.agent_datetime(19000101,  run_duration) ,'HH:mm:ss')
end [Duriation in HH:MM:SS]
FROM   msdb.dbo.sysjobs j
       INNER JOIN msdb.dbo.sysjobhistory h
               ON j.job_id = h.job_id
WHERE  j.enabled = 1
ORDER  BY run_duration DESC 


Using DISTINCT to Generate Combined Column List with Different Order by Column


 Create table Prods (prc_id int, prc_NAME varchar(10), prc_idgrp int)
Insert into Prods values(1,'D',25),(2,'A',25),(3,'C',25),(4,'B',25)

 declare @xlist varchar(1000)

;with mycte as (
Select distinct prc_ID, prc_NAME from PRODS

 SELECT @xlist=Stuff(( SELECT ',' + quotename(Cast(prc_ID as varchar(5)),']')
  FROM mycte
 Order by prc_NAME            
 FOR XML PATH(''), TYPE).value('.', 'varchar(max)'),1,1,'')   


Print @xlist
 drop table Prods