Thursday, January 14, 2021

Recently Executed queries

 SELECT

    txt.TEXT AS [SQL Statement],

    qs.EXECUTION_COUNT [No. Times Executed],

    qs.LAST_EXECUTION_TIME AS [Last Time Executed], 

    DB_NAME(txt.dbid) AS [Database]

FROM SYS.DM_EXEC_QUERY_STATS AS qs

    CROSS APPLY SYS.DM_EXEC_SQL_TEXT(qs.SQL_HANDLE) AS txt

ORDER BY qs.LAST_EXECUTION_TIME DESC

Wednesday, December 16, 2020

Convert Rows to 1 column - STRING_AGG - with order by




 select Col1, Col2, Col3, STRING_AGG( Col4,',')  WITHIN GROUP (ORDER BY Col4) as AggregatedColumn  from MyTable

group by Col1,Col2,Col3


Tuesday, August 18, 2020

Create a view with ORDER BY clause

 Msg 1033, Level 15, State 1, Procedure xxxx , Line 105 [Batch Start Line 0]

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.



As the error message suggested use


SELECT TOP 9999999  "fromYourQuery" ORDER BY something

Wednesday, July 1, 2020

Set Default Arguments for Stored Procedure Parameters

ALTER   PROCEDURE [myProcName]
@reportingPeriodFrom varchar(10)= NULL,@reportingPeriodTo varchar(10)=NULL, @useParam int=0
AS
BEGIN
if @useParam=1
BEGIN

print('PassArugments are used')
END
else
BEGIN]

set @reportingPeriodFrom = convert(date,concat(year(getdate()),'-',month(DATEADD(MONTH,-1, getdate())),'-01') )
set @reportingPeriodTo = convert(date,concat(year(getdate()),'-',month(getdate()),'-01'))
declare @FromDate varchar(12) =concat(year(getdate()),'-',month(DATEADD(MONTH,-1, getdate())),'-01')
declare @toDate varchar(12) = concat(year(getdate()),'-',month(getdate()),'-01')

raiserror('Executing Proc with From Data %s  to EndDate %s'  ,1,0,@FromDate,@toDate ) with nowait
print ( concat(convert(varchar,@reportingPeriodFrom),convert(varchar,@reportingPeriodTo)) ) 

end

Thursday, May 14, 2020

How to make LEFT JOIN depend on a further INNER JOIN - ( Filtering a left join further )



Below is how to make LEFT JOIN depend further on an INNER JOIN. Below is an example of "using LEFT JOIN and INNER JOIN in the same query":

SELECT *
FROM TableFoo tf1
LEFT JOIN (TableBar tb1
  INNER JOIN TableBaz tb2 ON tb2.id = tb1.baz_id
) ON
  tb1.id = tf1.bar_id


In this example, tb1 will only be included if tb2 is also found.

Monday, April 6, 2020

How to search/FIND for a text in body of Procedure.



SELECT name
FROM   sys.procedures
WHERE  Object_definition(object_id) LIKE '%TextYouWantToSearch%'


select * from sys.syscomments c
inner join sys.objects o on c.id=o.object_id
inner join sys.schemas s on s.schema_id=o.schema_id
where text like '%dim%'

Recently Executed queries

 SELECT     txt.TEXT AS [SQL Statement],     qs.EXECUTION_COUNT [No. Times Executed],     qs.LAST_EXECUTION_TIME AS [Last Time Executed],   ...