Archive for the ‘SQL’ Category

h1

Fetch stored procedure which contains “text”

June 4, 2015

Code :

SELECT ROUTINE_NAME, ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE ‘%texttosearch%’
AND ROUTINE_TYPE = ‘PROCEDURE’
h1

Get LASTINDEX in SQL

June 28, 2012

First create a function as folloing.

CREATE FUNCTION
CREATE FUNCTION dbo.LAST_INDEX(@STRING VARCHAR(8000), @CHAR CHAR)
RETURNS INT
AS
BEGIN
RETURN LEN(@STRING) – CHARINDEX(@CHAR, REVERSE(@STRING), 1 + 1)
END

Now you can use this like

SELECT LAST_INDEX(‘TEST.STRING’,’.’)

 

h1

SQL Alpha-Numeric Column Sorting

May 12, 2012

First create a function as folloing.

CREATE FUNCTION fn_AlphaNumSorting
(
@input varchar(max)
)
RETURNS varchar(max)
AS
BEGIN
declare @num varchar(50)
declare @space varchar(50)
declare @index int
set @index = 1set @num = LEFT(SUBSTRING(@input, PATINDEX(‘%[0-9.-]%’, @input), 8000), PATINDEX(‘%[^0-9.-]%’, SUBSTRING(@input, PATINDEX(‘%[0-9.-]%’, @input), 8000) + ‘X’)-1)
set @space = replicate(‘ ‘, 20 – len(@num))return replace(@input, @num, @space + @num)
END

Now you can use this like

select * from <tableName> order by dbo.fn_AlphaNumSorting(<columnName>)
h1

Select records with Latest Date

March 8, 2011

Using ROW_NUMBER we can select records with latest date.

ROW_NUMBER  Syntax

ROW_NUMBER ( ) OVER ( [ <partition_by_clause> ] <order_by_clause> )

Example

select * from
(select <column1>,<column2>,<column3>,
ROW_NUMBER() OVER (PARTITION BY <column1> ORDER BY <dateColumn> DESC) AS ‘RowNumber’
from tablename
where condition
) A where RowNumber = 1