Friday, October 25, 2013

Using Coalesce and quotename in sql

COAlesce(expression n)
works same as isnull but
 returns highest precision value of not null value as result
also if all the value are null coalesce returns null value but isnull returns not null value.
coalesce esecutes more than once to get result
but isnull is a function and hence executes only ones to get result

QUOTENAME(ColumnName)
returns [ColumnName]
use: to get name of columns for pivoting.

example:
Declare @JVNO nvarchar(200)
select @JVNO=
COALESCE(@JVNO+', ','') +QuoteName(JVNo,'''')
from (select distinct JVNo     from tbl_incomejournaldetails inner join tbl_incomeJournalmaster on tbl_incomeJournalmaster .JournalVoucherID =tbl_incomejournaldetails .JournalVoucherID
inner join tbl_LedgerMaster on tbl_incomejournaldetails .LedgerMasterID=tbl_LedgerMaster .LedgerMasterID
where tbl_LedgerMaster .Code='Previous Year') as B
Order By B.JVNo
--print @JVNO

declare @sql nvarchar(max)
set @sql='select * from tbl_incomejournaldetails inner join tbl_incomeJournalmaster
on tbl_incomeJournalmaster.JournalVoucherID =tbl_incomejournaldetails.JournalVoucherID
where JVNo   in ('+@JVNO+')'
--print @sql
exec( @sql)

No comments:

Post a Comment