How to remove first and last charcter if character is ',' of name in Sql query - sql

I combine two column value with ',' using below query.
SELECT
RTRIM(LTRIM(REPLACE(
IsNull(tbl1 .Reason,'') + ',' + IsNull(tbl2.OtherReason,''),',' ,'')))
FROM tbl1
LEFT JOIN tbl2 ON tbl2.OtherReasonId = tbl1.ReasonId
Now issue is that it remove all ',' using above query and I want to just remove last and first ','.
I have combine two column. Now
if tbl1 .Reason is null then it display output as " ,tbl2.OtherReason " and if tbl2.OtherReason is null the output is "tbl1 .Reason,"
Before above query, I also try with below query:
SELECT
IsNull(tbl1.Reason,'') + ',' + IsNull(tbl2.OtherReason,'')
FROM tbl1
LEFT JOIN tbl2 ON tbl2.OtherReasonId = tbl1.ReasonId
Thanks,
HItesh

You can use a case in the middle to check if the values are null or not.
declare #a nvarchar(5)
,#b nvarchar(5)
set #a = 'abc'
set #b = null--'123'
select isnull(#a, '') + case when #a is not null and #b is not null then ',' else '' end + isnull(#b, '')

Try this:
SELECT
CASE
WHEN tbl1.Reason IS NULL
THEN
CASE
WHEN tbl2.Reason IS NULL
THEN ''
ELSE LTRIM(RTRIM(tb2.Reason))
END
ELSE tbl1.Reason +
CASE
WHEN tbl2.Reason IS NULL
THEN ''
ELSE ',' + LTRIM(RTRIM(tb2.Reason))
END
END
FROM tbl1
LEFT JOIN tbl2 ON tbl2.OtherReasonId = tbl1.ReasonId

You can concatenate a comma to the first value in case that second value is not null :
SELECT
IsNull(tbl1.Reason + case when tbl2.OtherReason is null then '' else ',' end, '') +
IsNull(tbl2.OtherReason,'')
FROM tbl1
LEFT JOIN tbl2 ON tbl2.OtherReasonId = tbl1.ReasonId

Related

COALESCE Doubles results values

in function
SELECT #ProcedureName = COALESCE(#ProcedureName + ',', '') + ProcedureName
FROM V_Procedures P
inner join MedicalRecords MR on P.Medical_Record=MR.Medical_Record
where ProcedureName IS NOT NULL and MR.Admission_No  = #Admission_No
and Field = 18
getting many doubles seperated by comma, is it possible to avoid it?
For example results values appears more then once as
CONCHOTOMY,FESS-FUNCTIONAL ENDOSCOPIC (NASAL) SINUS SURGERY,CONCHOTOMY,FESS-FUNCTIONAL ENDOSCOPIC (NASAL) SINUS SURGERY,SUBMUCOUS RESECTION OF NASAL SEPTUM
You seems want distinct :
SELECT DISTINCT #ProcedureName = COALESCE(#ProcedureName + ',', '') + ProcedureName
FROM V_Procedures P INNER JOIN
MedicalRecords MR
ON P.Medical_Record=MR.Medical_Record
WHERE ProcedureName IS NOT NULL AND
MR.Admission_No = #Admission_No AND
Field = 18;
Instead COALESCE, try with CONCAT. And also GROUP BY.
DECLARE #ProcedureName VARCHAR(max);
SELECT #ProcedureName = CONCAT(#ProcedureName + ',', ProcedureName)
FROM V_Procedures P
JOIN MedicalRecords MR ON P.Medical_Record = MR.Medical_Record
WHERE ProcedureName IS NOT NULL AND MR.Admission_No = #Admission_No
AND Field = 18
GROUP BY ProcedureName
The trick is that CONCAT won't return NULL when a NULL is added to it. But + does. So because #ProcedureName is NULL at first, the result won't start with a comma.

How to have a NULL instead of No Value from a query

I had a query like:
SELECT ISNULL(S.Name+'.'+T.Name,'Table Not Found')
FROM DataProfile.Tables T
INNER JOIN DataProfile.Schemas S ON T.schemaId=S.Id
WHERE S.Name+'.'+T.Name=#TableName
Then I tried
IIF(LEN(S.Name+'.'+T.Name)>0,S.Name+'.'+T.Name,NULL)
But when it doesn't find the named table returns not output, Value or Null value or anything I can work on.
This is going to be used as a crosscheck.
Does anybody have any idea?
Thanks for those who payed attention to what I exactly asked and for their responses.
Here the way I tried:
DECLARE #Check NVARCHAR(MAX) = 'TABLE DOES NOT FOUND'
SELECT #Check= S.Name + '.' + T.Name
FROM DataProfile.Tables T
INNER JOIN DataProfile.Schemas S ON T.schemaId=S.Id
WHERE S.Name+'.'+T.Name=#TableName
SELECT #CHECK
And That Worked for me
this will always return a row:
select v.TableName, ISNULL(found.result, 'not found') result
from (values(#TableName))v(TableName)
outer apply (
select CAST('found' as nvarchar(11)) result
from DataProfile.Tables T
join DataProfile.Schemas S ON T.schemaId=S.Id
where S.Name+'.'+T.Name=v.TableName
)found
you should try this
SELECT CASE WHEN (LEN(S.Name + '.' + T.Name))> 1 THEN S.Name + '.' + T.Name ELSE NULL END
So you qry will look like
SELECT CASE
WHEN (LEN(S.Name + '.' + T.Name))> 1 THEN
S.Name + '.' + T.Name
ELSE
NULL -- Here use any expresion which you want
END
FROM DataProfile.Tables T
INNER JOIN DataProfile.Schemas S ON T.schemaId=S.Id
WHERE S.Name+'.'+T.Name=#TableName
Here you are using ISNULL(S.Name+'.'+T.Name,'Table Not Found') which never return false part due to if S.Name and T.Name both are null then still that value will be '.'
Try doing it this way:
with table_qry as
(
select S.Name as SName, T.Name as TName
from DataProfile.Tables T
inner join DataProfile.Schemas S
on T.SchemaId = S.Id
where S.Name+'.'+T.Name = #TableName
)
select case when (select count(1) from table_qry) > 0 then
SName+'.'+TName else 'Table Not Found' end as TableName
from table_qry;
There are more elegant ways of doing it, but this should work just fine for you.

error- Each column has to have a unique name when you’re returning the query

I am trying to run reporting services with below SQL query
select ca.callingpartynumber, ca.originalcalledpartynumber, case
when calledpartylastname is not null then ca.calledpartylastname + ',' + calledpartyfirstname
else p1.name end,
p1.location, p1.dept, p1.title,
case
when callingpartylastname is not null then ca.callingpartylastname + ',' + callingpartyfirstname
else p3.name end
from calldata.calldetailreport ca
join ps_bc_peoplesource_base p1 on ca.originalcalledpartynumber = replace(p1.bc_int_phone, '-', '')
left outer join ps_bc_peoplesource_base p3 on ca.callingpartynumber = replace(p1.bc_int_phone, '-', '')
where originalcalledpartynumber in (select replace(bc_int_phone, '-', '') internal_modified from ps_bc_peoplesource_base where bc_lan_id = 'f7c')
--and datetimedisconnect between #startdate and #enddate --1221
I get this error-
“An item with the same key has already been added.”
You are missing Column Alias for Two Case Statement in Your SELECT query. As SSRS uses only the column name as the key, not table + column, so it was choking.
Refer Here And Here And Here also
SELECT ca.callingpartynumber, ca.originalcalledpartynumber,
CASE WHEN calledpartylastname IS NOT NULL
THEN ca.calledpartylastname + ',' + calledpartyfirstname
ELSE p1.name END AS calledpartylastname,
p1.location,
p1.dept,
p1.title,
CASE WHEN callingpartylastname IS NOT NULL
THEN ca.callingpartylastname + ',' + callingpartyfirstname
ELSE p3.name END AS callingpartylastname
...
...

Case within Case when combining multiple columns into one

I'm trying to create a query that will take multiple columns in a View and bring it into one column in the query. The values from each column needs to be separated by '|' (pipe).
I've tried:
1) (expression1 + '|' + expression2) AS xxxx, but if one expression has a null value, it makes the results 'null'.
2) CAST (expression1 as varchar (10)) + '|' + CAST (expression2 as varchar (10)) AS xxxx, but get the same results.
3) CASE (expression1 is null) then (' ') else (expression1) +'|' + CASE (expression2 is null) then (' ') else (expression2) END AS xxxx, but I get a syntax error near the keyword 'AS'.
Here's the full query using CASE.
SELECT DISTINCT dbo.REG.BUILDING, dbo.REG.CURRENT_STATUS, dbo.REG_CONTACT.LOGIN_ID, dbo.REG.LAST_NAME
, CASE WHEN dbo.View_MYAccess_Period1.CRSGRP1 is null then ' ' else dbo.View_MYAccess_Period1.CRSGRP1 + ' |' +
CASE WHEN dbo.View_MYAccess_Period2.CRSGRP2 is null then ' ' else dbo.View_MYAccess_Period2.CRSGRP2
END AS CRSGRP
FROM dbo.REG_CONTACT RIGHT OUTER JOIN
dbo.REG_STU_CONTACT ON dbo.REG_CONTACT.CONTACT_ID = dbo.REG_STU_CONTACT.CONTACT_ID RIGHT OUTER JOIN
dbo.REG ON dbo.REG_STU_CONTACT.STUDENT_ID = dbo.REG.STUDENT_ID LEFT OUTER JOIN
dbo.View_MYAccess_Period1 ON dbo.REG.STUDENT_ID = dbo.View_MYAccess_Period1.STUDENT_ID LEFT OUTER JOIN
dbo.View_MYAccess_Period2 ON dbo.REG.STUDENT_ID = dbo.View_MYAccess_Period2.STUDENT_ID
Any help for this newbie would be greatly appreciated!
Use ISNULL function,
SELECT DISTINCT dbo.REG.BUILDING, dbo.REG.CURRENT_STATUS, dbo.REG_CONTACT.LOGIN_ID, dbo.REG.LAST_NAME
, ISNULL(dbo.View_MYAccess_Period1.CRSGRP1,' ') + ' |' +
ISNULL(dbo.View_MYAccess_Period2.CRSGRP2,' ') CRSGRP
FROM dbo.REG_CONTACT RIGHT OUTER JOIN
dbo.REG_STU_CONTACT ON dbo.REG_CONTACT.CONTACT_ID = dbo.REG_STU_CONTACT.CONTACT_ID RIGHT OUTER JOIN
dbo.REG ON dbo.REG_STU_CONTACT.STUDENT_ID = dbo.REG.STUDENT_ID LEFT OUTER JOIN
dbo.View_MYAccess_Period1 ON dbo.REG.STUDENT_ID = dbo.View_MYAccess_Period1.STUDENT_ID LEFT OUTER JOIN
dbo.View_MYAccess_Period2 ON dbo.REG.STUDENT_ID = dbo.View_MYAccess_Period2.STUDENT_ID
In example 1, you might use the COALESCE(expression, fallback) function to force expression to return a fallback value if the expression is null. (Then tweak the rest of the logic accordingly.)
In your example 3, you need another END keyword:
CASE
(expression1 is null) then (' ')
ELSE (expression1) +'|' +
CASE (expression2 is null) then (' ') else (expression2) END
END AS xxxx

SQL Server Comma Separated value among columns

I want to select columns as comma-separated values by doing something like:
select column1+','+column2+','+column3+','+coulmn4 from someTable
except if any of the columns hold null values i have to skip that column from adding comma
how to do this is SQL Server?
[All columns are of type varchar so no casting needed]
Select
Case When Len(IsNull(Column1),'') > 0 Then Column1 + ',' Else '' End,
Case When Len(IsNull(Column2),'') > 0 Then Column2 + ',' Else '' End,
Case When Len(IsNull(Column3),'') > 0 Then Column3 + ',' Else '' End,
Case When Len(IsNull(Column4),'') > 0 Then Column4 + ',' Else '' End,
Case When Len(IsNull(ColumnN),'') > 0 Then ColumnN + ',' Else '' End
From
SomeTable
try
Test table
create table #testCol (column1 varchar(10), column2 varchar(10),
column3 varchar(10), column4 varchar(10))
insert #testCol values('a', null,null,'b')
insert #testCol values(null,'a',null,'b' )
insert #testCol values(null,'a','Z','b' )
Query
select isnull(column1,'')+ case when column1 is null then '' else ',' end
+ isnull(column2,'')+ case when column2 is null then '' else ',' end
+ isnull(column3,'')+ case when column3 is null then '' else ',' end
+ isnull(column4,'')
from #testCol
Output
a,b
a,b
a,Z,b
Can you export to csv and then strip out all the double commas?
select isnull(column1 + ',', '') + isnull(column2 + ',', '') + isnull(column3 + ',', '') + isnull(coulmn4, '') from someTable