Thursday, 18 September 2014

SQL: Column Values as Comma Separated String

I have a table as shown below, which has Country_Code and languages that are spoken by different people living in a country. I need to retrieve distinct languages spoken in a country based on the Country_Code column as a comma separated string.

SQL Statement

The following statement shows how it can be achieved:
declare @str varchar(1000)

SELECT @str= coalesce(@str + ', ', '') + a.CountryLang_Desc 
FROM (SELECT DISTINCT CountryLang_Desc from CountryLanguages where Country_Code='IN') a

print @str 

Wednesday, 3 September 2014

Split Function in Sql Server 2008

create a Split Function using below code


CREATE FUNCTION [dbo].[Split]
(
@String NVARCHAR(4000),
@Delimiter NCHAR(1)
)
RETURNS TABLE 
AS
RETURN 
(
WITH Split(stpos,endpos) 
AS(
SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos
UNION ALL
SELECT endpos+1, CHARINDEX(@Delimiter,@String,endpos+1)
FROM Split
WHERE endpos > 0
)
SELECT 'Id' = ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
'Data' = SUBSTRING(@String,stpos,COALESCE(NULLIF(endpos,0),LEN(@String)+1)-stpos)
FROM Split
)
GO


EX:- CompanyAddress =dsfsdf `Adhaura`Bihar`India

calling this function using below code

select data from dbo.Split(CompanyAddress,'`')where id = 2

o/p:- Adhaura

SQL SERVER – Disk Space Monitoring – Detecting Low Disk Space on Server

CREATE PROCEDURE [CSMSDVLP].[DiskSpaceMonitor] @mailProfile nvarchar(500), @mailto nvarchar(4000), @threshold INT, @logfile nvarchar(40...