Concatenation Statement - sql-server

I am using a concatenation statement to return Last Name, First Name Middle initial with a period (.). Ex: “Brown, John R.”. The statement is as follows:
IF([Middle Name] IS NULL )
THEN (trim([Last Name])+', '+trim([First Name]))
ELSE (trim([Last Name])+', '+trim([First Name])+' '+substring(nullif([Middle Name],' '),1,1)+'.'))
However, the statement is randomly omitting several of the names in the returned result. If I do not use the "nullif" option, it still returns periods where there is no middle initial.
Any help would be appreciated.
Thanks

How about replace the whole thing with:
SELECT trim([Last Name])+', '+trim([First Name]) + Isnull(' ' + LEFT([Middle NAME],1) + '.','') AS FullName
Are all the first and last names filled in (NOT Null)?

Related

how to use a sql substring in a where in string list conditional

I have a where conditional
where
pnumber in ('mem1234', 'mem2345','mem8978')
I need a substring without the mem in this where conditional. There are a couple hundred strings in this where conditional.
What is the syntax for this?
In order to manipulate the data you will first need to insert it into a temp table/ table variable and then depending on how consistant your data is you could try the following:
DECLARE #pNumbers TABLE (item varchar(20))
insert into #pNumbers values('mem1234'),('mem2345'),('mem8978')
select
REPLACE(item, 'mem', '') AS ReplaceMethod ,
SUBSTRING(item, 4, 4) AS SubstringMethod,
RIGHT(item,LEN(item) - 3) AS Right_LenMethod
FROM #pNumbers
You would then add one of them methods to a subquery in the WHERE
WHERE
pnumber IN ( SELECT REPLACE(item, 'mem', '') FROM #pNumbers )
Or as others have stated, you could open the csv in an external program and find and replace but atleast you have options

How to remove space when concatenating data from different rows into one column using xml?

I am trying to combine data from different rows into one column, and this is working with just one minor problem.
declare #RitID int = 16
select ...,
( select distinct
ISNULL(LTRIM(RTRIM(r2.LotNr)), LTRIM(RTRIM(r.LotNr))) + '+' as 'data()'
from tblExtraBestemming eb2
inner join tblRit r2 on eb2.RitID = r2.RitID
where eb2.BestemmingID = eb.BestemmingID
and eb2.BestemmingTypeID = eb.BestemmingTypeID
and ( (eb.CombinedChildExtraBestemmingID is null and eb2.RitID = #RitID)
or
(eb.CombinedChildExtraBestemmingID is not null and eb2.RitID in (select r4.RitID from tblRit r4 where r4.MasterRitID = #RitID) )
)
for XML PATH('')
) as LotNr
from tblExtraBestemming eb
where ...
this returns the correct data for the column LotNr, like this
GTT18196
GTT18197
GTT18198+ GTT18199
Now my only problem is the space after the + sign in the third row from the result, how can I get rid of this ?
I expect this result
GTT18196
GTT18197
GTT18198+GTT18199
PS, actually there is also a + at the end of each row, but that is removed by the client. I thought I better mentions this already.
EDIT
I checked the data, there are no spaces at the end or the beginning of the data
EDIT
Query updated as suggested by #Larnu
EDIT
if I check the data in the table, this is the result
select '/' + r.LotNr + '/' from tblRit r where r.RitID in (50798, 50799)
COLUMN1
-------
/GTT18198/
/GTT18199/
So it appears to me there are no characters before or after the data
Just remove AS 'data()' from your query (it is not required in the above case).
And if trailing + is a problem, move it to the beginning and use STUFF function to chop off the first character from the result.

In SQL Server, REPLACE function is not working properly when I use to replace with 1 space

select
replace(WBSElem, appProj, '') AS WBSElement,
replace(WBSElem + '#' + Descrip, '', '') as Descrip,
*
from
SAP_sFTP_DB.dbo.MMHE_PS_WBS
where
appProj = '1.13T0117'
order by
RecID asc
Here second replace is working fine, but the 1st replace is not working properly where I have above 100 records to change. I am getting output like nothing happened for 1st replace function. Can anybody help me?
select replace(WBSElem, rtrim(ltrim(appProj)), '') AS WBSElement,
replace(WBSElem+'#'+Descrip,'','')as Descrip, * from SAP_sFTP_DB.dbo.MMHE_PS_WBS where appProj='1.13T0117'
Due to White spaces the function did'nt work.Now its fine

Query fails on "converting character string to smalldatetime data type"

I've been tasked with fixing some SQL code that doesn't work. The query reads from a view against a predicate. The query right now looks like so.
SELECT TOP (100) Beginn
FROM V_LLAMA_Seminare
//Removal of the following line makes the query successful, keeping it breaks it
where Beginn > (select cast (getdate() as smalldatetime))
order by Beginn desc
When I run the above query, I am greeted with the following error.
Msg 295, Level 16, State 3, Line 1
Conversion failed when converting character string to smalldatetime data type.
I decided to remove the WHERE clause, and now it runs returning 100 rows.
At first, I thought that behind the scenes, SQL Server was somehow including my predicate when bringing back the View . But then I investigated how the View was being created, especially the Beginn field, and at no point does it return a String.
Long story short, the column that becomes the Beginn field is a BIGINT timestamp like 201604201369.... The original user transforms this BIGINT to a smalldatetime using the following magic.
....
CASE WHEN ma.datum_dt = 0
THEN null
ELSE CONVERT(smalldatetime, SUBSTRING(CAST(ma.datum_dt AS varchar(max)),0,5) + '-' +
SUBSTRING(CAST(ma.datum_dt AS varchar(max)),5,2) + '-' +
SUBSTRING(CAST(ma.datum_dt AS varchar(max)),7,2) + ' ' +
SUBSTRING(CAST(ma.datum_dt AS varchar(max)),9,2) +':'+
SUBSTRING(CAST(ma.datum_dt AS varchar(max)),11,2) +':' +
RIGHT(CAST(ma.datum_dt AS varchar(max)),2)) END AS Beginn
...
My last attempt at finding the problem was to query the view and run the function ISDATE over the Beginn column and see if it returned a 0 which it never did.
So my question is two fold, "Why does a predicate break something" and two "Where on earth is this string error coming from when the Beginn value is being formed from a BIGINT".
Any help is greatly appreciated.
This problem is culture related...
Try this and then change the first SET LANGUAGE to GERMAN
SET LANGUAGE ENGLISH;
DECLARE #bi BIGINT=20160428001600;
SELECT CASE WHEN #bi = 0
THEN null
ELSE CONVERT(datetime, SUBSTRING(CAST(#bi AS varchar(max)),0,5) + '-' +
SUBSTRING(CAST(#bi AS varchar(max)),5,2) + '-' +
SUBSTRING(CAST(#bi AS varchar(max)),7,2) + ' ' +
SUBSTRING(CAST(#bi AS varchar(max)),9,2) +':'+
SUBSTRING(CAST(#bi AS varchar(max)),11,2) +':' +
RIGHT(CAST(#bi AS varchar(max)),2)) END AS Beginn
It is a very bad habit to think, that date values look the same everywhere (Oh no, my small application will never go international ...)
Try to stick to culture independent formats like ODBC or ISO
EDIT
A very easy solution for you actually was to replace the blank with a "T"
SUBSTRING(CAST(ma.datum_dt AS varchar(max)),7,2) + 'T' +
Then it's ISO 8601 and will convert...
The solution was found after looking through #Shnugo's comment. When I took my query which contained the Bigint->Datetime conversion logic, and put it into a CTE with "TOP 100000000" to avoid any implicit conversion actions, my query worked. Here is what my view looks like now with some unimportant parts omitted.
---Important part---
CREATE VIEW [dbo].[V_SomeView] AS
WITH CTE AS (
SELECT TOP 1000000000 ma.id AS MA_ID,
---Important part---
vko.extkey AS ID_VKO,
vko.text AS Verkaufsorganisation,
fi.f7000 AS MDM_Nr,
vf.f7105 AS SAPKdnr,
CASE WHEN ma.datum_dt = 0 --Conversion logic
CASE WHEN ma.endedatum_dt = 0 --Conversion logic
CONVERT(NVARCHAR(MAX),art.text) AS Art,
.....
FROM [ucrm].[dbo].[CRM_MA] ma,
[ucrm].[dbo].[CRM_fi] fi,
[ucrm].[dbo].[CRM_vf] vf,
[ucrm].[dbo].[CRM_ka] vko,
[ucrm].[dbo].[CRM_ka] art,
[ucrm].[dbo].[CRM_ka] kat
where ma.loskz = 0
and fi.loskz = 0
and vf.loskz = 0
and fi.F7029 = 0
and vf.F7023 = 0
...
GROUP BY ma.id,
vko.extkey,
vko.text,
fi.f7000 ,
vf.f7105,
ma.datum_dt,
ma.endedatum_dt,
....
)
select * FROM CTE;

Oracle split text into multiple rows

Inside a varchar2 column I have text values like :
aaaaaa. fgdfg.
bbbbbbbbbbbbbb ccccccccc
dddddd ddd dddddddddddd,
asdasdasdll
sssss
if i do select column from table where id=... i get the whole text in a single row, normally.
But i would like to get the result in multiple rows, 5 for the example above.
I have to use just one select statement, and the delimiters will be new line or carriage return (chr(10), chr(13) in oracle)
Thank you!
Like this, maybe (but it all depends on the version of oracle you are using):
WITH yourtable AS (SELECT REPLACE('aaaaaa. fgdfg.' ||chr(10)||
'bbbbbbbbbbbbbb ccccccccc ' ||chr(13)||
'dddddd ddd dddddddddddd,' ||chr(10)||
'asdasdasdll ' ||chr(13)||
'sssss '||chr(10),chr(13),chr(10)) AS astr FROM DUAL)
SELECT REGEXP_SUBSTR ( astr, '[^' ||chr(10)||']+', 1, LEVEL) data FROM yourtable
CONNECT BY LEVEL <= LENGTH(astr) - LENGTH(REPLACE(astr, chr(10))) + 1
see: Comma Separated values in Oracle
The answer by Kevin Burton contains a bug if your data contains empty lines.
The adaptation below, based on the solution invented here, works. Check that post for an explanation on the issue and the solution.
WITH yourtable AS (SELECT REPLACE('aaaaaa. fgdfg.' ||chr(10)||
'bbbbbbbbbbbbbb ccccccccc ' ||chr(13)||
chr(13)||
'dddddd ddd dddddddddddd,' ||chr(10)||
'asdasdasdll ' ||chr(13)||
'sssss '||chr(10),chr(13),chr(10)) AS astr FROM DUAL)
SELECT REGEXP_SUBSTR ( astr, '([^' ||chr(10)||']*)('||chr(10)||'|$)', 1, LEVEL, null, 1) data FROM yourtable
CONNECT BY LEVEL <= LENGTH(astr) - LENGTH(REPLACE(astr, chr(10))) + 1;

Resources