COALESCE Doubles results values - sql

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.

Related

Unexpected output when executed

I have a problem in SQL Server, when I try to select two columns.
Here is the code I have written:
declare #d varchar(max)
set #d = ''
begin
select #d = #d + convert(nvarchar(MAX), R.Data, 121) + ('<table></td><td>' + convert(nvarchar(MAX), C.No) + '</td><td>' + C.Nome + '</td><td>' + convert(nvarchar(MAX), V.IdVendedor) + '</td><td>' + convert(nvarchar(MAX), V.Vendnm) + '</td></tr></table>')
from dbo.Reclamacoes R
Inner Join dbo.PHC_CLIENTES_SAMSYS C On R.IdCliente = C.Id
Inner Join dbo.PHC_VENDEDORES_SAMSYS V on R.IdVendedor = V.IdVendedor
select #d As Data, #d As HTML_COLUMN
end
It shows like this:
2019-02-07 00:00:00.0000000 " <table></td><td>2762.00</td><td>REGINA & MIGUEL, LDA. ( REMI )</td><td>78.00</td><td>AndreiaVeloso</td></tr></table> "
As you see, data is mixed with what is supposed to appear in the other column (I put in "" what it's supposed to appear in the other column).
And when I execute the column know as "Data" is mixed with " HTML_COLUMN.
And I'm trying to get two columns just with one variable.
Can someone tell me if is possible in my case, to have a query showing two columns when having just one variable? Thanks in advance.
You can make #d a Table Variable and put two columns in it.
Example from MSDN:
DECLARE #MyTableVar table(
EmpID int NOT NULL,
OldVacationHours int,
NewVacationHours int,
ModifiedDate datetime);
Try this..
DECLARE #HTML NVARCHAR(MAX) = '';
SET #HTML
= N'<table border="1" >'
+ N'<tr><th>Data</th><th>Nome</th><th>IdVendedor</th><th>Vendnm</th>'
+ CAST((
SELECT
td = R.Data
, ''
, td = C.Nome
, ''
, td = V.IdVendedor
, ''
, td = V.Vendnm
FROM dbo.Reclamacoes R
INNER JOIN dbo.PHC_CLIENTES_SAMSYS C ON R.IdCliente = C.Id
INNER JOIN dbo.PHC_VENDEDORES_SAMSYS V ON R.IdVendedor = V.IdVendedor
FOR XML PATH('tr'), TYPE
) AS NVARCHAR(MAX)) + N'</table>';
SELECT #HTML;

SQL Server - COALESCE WHEN NOTHING RETURNS , GET DEFAULT VALUE

I'm trying to use Coalesce function in SQL Server to concatente multiple names. But when the conditon in the query returns no rows or nothing, I need to return a default value. I tried some condition using case statement but I can't figure it out what I missed.
declare #Names varchar(max) = '',
#Key varchar(max) = 'ABC'
select #Names = COALESCE(#Names, '') + isnull(T0.A, #Key) + ', '
from TData P
left join TNames T0 on T0.C + '\' + T0.D = P.#Key
where OBID=581464
and ID < 1432081
select #Names
You can do it with 2 minor changes to your current code, but I suspect this is an XYProblem, and you might benefit more from editing your question to include sample data and desired results (so perhaps we can suggest a better solution).
Anyway, what I had in mind is this:
declare #Names varchar(max), -- remove the = '', so that #Names starts as null
#Key varchar(max) = 'ABC'
select #Names = COALESCE(#Names, '') + isnull(T0.A, #Key) + ', '
from TData P
left join TNames T0 on T0.C + '\' + T0.D = P.#Key -- ' (This is just to fix the coding colors)
where OBID=581464
and ID < 1432081
select COALESCE(#Names, 'default value') -- since #Names started as null, and the query did not return any results, it's still null...

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

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

Return comma-separated list from SQL Server

I have a stored procedure as below. Now I want to modify it so that it returns the value as a comma separated list.
CREATE PROCEDURE [dbo].[CUST_Notification_GetCompaniesFromEmails]
#EmailValue AS NTEXT
AS
SELECT DISTINCT
ISNULL(CompanyAddressesContacts.FirstName, '') + ' ' +
ISNULL(CompanyAddressesContacts.LastName, '') AS ContactName
,ISNULL(dbo.Companies.CompanyName,'') AS CompanyName,
CASE
WHEN CompanyName = 'Meraas Development' THEN '1'
WHEN CompanyName = 'Samsung C&T' THEN '2'
ELSE '3'
END AS id
FROM
dbo.CompanyAddressesContacts
INNER JOIN
dbo.Companies ON dbo.CompanyAddressesContacts.CompanyId = Companies.Id
WHERE
dbo.CompanyAddressesContacts.Email IN
(SELECT [value]
FROM dbo.SplitWords(#EmailValue,';'))
The above code returns values as a normal select statement would do . Now I want a modification in the code so that it returns a value as comma-separated list.
Thanks!
Try like this
DECLARE #List VARCHAR(8000)
SELECT #List = COALESCE(#List + ',', '') + CAST(OfferID AS VARCHAR)
FROM Emp
WHERE EmpID = 23
SELECT #List
Try to use SplitWords method as
dbo.SplitWords(#EmailValue +',','')
Have a visit
http://msmvps.com/blogs/robfarley/archive/2007/04/08/coalesce-is-not-the-answer-to-string-concatentation-in-t-sql.aspx
http://oops-solution.blogspot.in/2011/11/sql-server-convert-table-column-data.html

Operand type clash: varchar is incompatible with User-Defined Table Type

I created a User-Defined Table Type:
CREATE TYPE dbo.ListTableType AS TABLE(
ITEM varchar(500) NULL
)
I leverage it in a function:
CREATE FUNCTION dbo.fn_list_to_string
(
#LIST dbo.ListTableType READONLY
)
RETURNS varchar(max)
AS
BEGIN
DECLARE #RESULT varchar(max)
SET #RESULT = ''
DECLARE #NL AS CHAR(2) = CHAR(13) + CHAR(10)
SELECT #RESULT = #RESULT + ITEM + #NL FROM #LIST
SET #RESULT = SUBSTRING(#RESULT, 1, LEN(#RESULT) - 1)
RETURN #RESULT
END
Finally, I try to use this function in a simple select:
SELECT
P.PROGRAM_ID,
PROGRAM_NAME,
PROGRAM_DESC,
P.STATUS_ID,
STATUS_DESC,
P.CONTACT_SID,
I.FIRST_NAME + ' ' + I.LAST_NAME as CONTACT_NAME,
P.CLARITY_ID,
dbo.fn_list_to_string(
( SELECT CONVERT(varchar,CLARITY_ID) as ITEM
FROM dbo.MUSEUM_PROGRAM_PROJECTS as A
JOIN dbo.MUSEUM_PROJECTS as B on B.PROJECT_ID = A.PROJECT_ID
WHERE PROGRAM_ID = P.PROGRAM_ID )
) as PROJECT_CLARITY_IDS
FROM dbo.MUSEUM_PROGRAMS as P
LEFT JOIN dbo.MUSEUM_PROGRAM_STATUS_TYPES as S on S.STATUS_ID = P.STATUS_ID
LEFT JOIN dbo.v_IDVAULT_ENRICHED_CURRENT_EMPLOYEES as I on I.[SID] = P.CONTACT_SID
But I get this error:
Operand type clash: varchar is incompatible with ListTableType
Any idea why? Also if there's another [more elegant] way to achieve what I'm trying to do I'm open to suggestions as well! Thanks in advance!
Here is a simple demonstration of the FOR XML PATH technique which does all of this with a very simple subquery and no table types or extremely inefficient multi-statement table-valued functions etc.
USE tempdb;
GO
CREATE TABLE dbo.P(Program_ID INT);
CREATE TABLE dbo.M(Clarity_ID INT, Program_ID INT);
INSERT dbo.P VALUES(1),(2),(3),(4);
INSERT dbo.M VALUES(1,1),(1,2),(2,3),(3,2),(1,4),(4,1);
SELECT
P.PROGRAM_ID,
PROJECT_CLARITY_IDS = STUFF((
SELECT CHAR(13)+CHAR(10)+CONVERT(VARCHAR(12),Clarity_ID)
FROM dbo.M WHERE Program_ID = p.Program_ID
FOR XML PATH(''), TYPE).value('.[1]','nvarchar(max)'),1,2,'')
FROM dbo.P AS p;
SQLfiddle demo
The output doesn't look right in SQLfiddle or in results to grid in Management Studio, because they strip out carriage returns/line feeds for display purposes, but you can replace CHAR(13)+CHAR(10) with two commas or semi-colons or something to verify that there are two characters there.
Using STUFF..FOR XML PATH construct for concatanation in combination with CTE will get the results you'd like. Something like this:
WITH CTE_PROJECT_CLARITIES AS
(
SELECT DISTINCT PROGRAM_ID
, STUFF((
SELECT CHAR(13) + CHAR(10) + CONVERT(varchar(11),CLARITY_ID)
FROM dbo.MUSEUM_PROGRAM_PROJECTS as A
JOIN dbo.MUSEUM_PROJECTS as B on B.PROJECT_ID = A.PROJECT_ID
WHERE A.PROGRAM_ID = X.PROGRAM_ID
FOR XML PATH ('')),1,2,'') AS PROJECT_CLARITY_IDS
FROM MUSEUM_PROGRAM_PROJECTS X
)
SELECT
P.PROGRAM_ID,
PROGRAM_NAME,
PROGRAM_DESC,
P.STATUS_ID,
STATUS_DESC,
P.CONTACT_SID,
I.FIRST_NAME + ' ' + I.LAST_NAME as CONTACT_NAME,
P.CLARITY_ID,
X.PROJECT_CLARITY_IDS
FROM dbo.MUSEUM_PROGRAMS as P
LEFT JOIN dbo.MUSEUM_PROGRAM_STATUS_TYPES as S on S.STATUS_ID = P.STATUS_ID
LEFT JOIN dbo.v_IDVAULT_ENRICHED_CURRENT_EMPLOYEES as I on I.[SID] = P.CONTACT_SID
LEFT JOIN CTE_PROJECT_CLARITIES X ON X.PROGRAM_ID = p.PROGRAM_ID
SQLFiddle DEMO (not sure if I got the columns right, but you'll get the idea)