Why Does string_agg Not Make Changes In This Context - tsql

I was starting down the road of testing within group(), and I came across this unexpected behavior of string_agg (or maybe substring). In the following code, mType is a field containing things like 'HMA - etc.etc.etc.' or 'ACP - etc.etc.etc.' In the following context, the 2nd selected field fails to change the delimiter from a ',' to a '-'
select string_agg( substring( mType,1,3 ), ',' ) mType
,string_agg( substring( mType,1,3), '-' ) mType2
from ourDB..mTypeTable
where ref = '3944900'
Returns:
If I change the substring from 1,3 to 1,4, then things work.
select string_agg( substring( mType,1,3 ), ',' ) mType
,string_agg( substring( mType,1,4), '-' ) mType2
from ourDB..mTypeTable
where ref = '3944900'
Returns:
Why does TSQL fail to change the delimiter in the first context? Is this some kind of optimization moment or something where TSQL is reusing the last substring because it's pulling from the same field in the same table in the same select?

Related

How to add a single quote before each comma

a have a column as below
mystring
AC1853551,AC1854125,AC1855220,AC188115,AC1884120,AC1884390,AC1885102
I need to transformm it to get this output
mystring
('AC1853551','AC1854125','AC1855220','AC188115','AC1884120','AC1884390','AC1885102')
Here is my query that i tried
select CONCAT('( , CONCAT (mystring, ')')) from mytablename
I'm getting an error when it comes to insert a single quote '
Then i thought about replacing the comma with a ','
How to get desired output
i'm using postgres 10
A literal quote is coded as a doubled quote:
select '(''' || replace(mycolumn, ',', ''',''') || ''')'
from mytable
See live demo.

Trying to extract text using CHARINDEX ()- 1 but getting an error

I have a column with Names, and I am trying to split the column into First and Last Name using Text functions such as LEFT/SUBSTRING/CHARINDEX.
Data in the column:
Name
Yang, Jon
Huang, Eugene
Torres, Ruben
Zhu, Christy
Johnson, Elizabeth
Everything works fine as long as I use this code:
SELECT
[Name]
--,LEFT([Name], CHARINDEX(' ', [Name])) AS FirstName
,SUBSTRING([Name], 1, CHARINDEX(' ', [Name] )) AS FirstName
FROM
DataModeling.Customer
But the problem arises when I try to subtract 1 from CHARINDEX to exclude the Comma from the result and it throws this error:
I have done this operation many times in Excel so trying to replicate it with TSQL. Any suggestion on what I am doing wrong is helpful.
You get that error when CHARINDEX(' ', [Name] ) return 0. So minus 1 will make it negative and it is invalid value for substring()
You can use CASE expression to check the return value from CHARINDEX() and return the correct value to substring()
Or, you can "cheat" by using
CHARINDEX( ' ', [Name] + ' ' )
So CHARINDEX() will always return a value that is more than 0

Split column into columns using split_part returning empty

I have a column stored as text in postgres 9.6. It's an address and some of the rows have format like BUILD NAME, 40
I saw this answer which looks like what i want, if i run;
select split_part('BUILD NAME, 40', ',', 2) as address_bldgno
It returns; 40 as I want.
When i try;
select
split_part(address, ', ', 1) as address_bldgname,
split_part(address, ', ', 2) as address_bldgno
from table;
It runs but returns empty values
As you mentioned:
...some of the rows have format...
I suspect anything that doesn't contain comma returns empty values.
That is due to the split_part condition does not find a match for the argument.
To illustrate how different address values are split here's some example:
WITH "table" ( address ) AS (
VALUES
( 'BUILD NAME, 40' ), -- first and second have value
( 'BUILD NAME' ), -- only first have value (bldgname)
( '40' ), -- only first have value (bldgname)
( ', 40' ), -- first is empty string, second is value
( 'BUILD NAME,' ), -- first is value, second is empty string
( NULL ), -- both are NULL
( '' ) -- no match found, both are empty strings
)
SELECT split_part( address, ', ', 1 ) as address_bldgname,
split_part( address, ', ', 2 ) as address_bldgno
FROM "table";
-- This is how it looks in result:
address_bldgname | address_bldgno
------------------+----------------
BUILD NAME | 40
BUILD NAME |
40 |
| 40
BUILD NAME, |
|
|
(7 rows)
If you want to set some defaults for NULL and empty string I recommend to read also: this answer
Answer found here;
PostgreSQL 9.3: Split one column into multiple
Should have been;
select somecol
,split_part(address, ', ', 1) as address_bldgname
,split_part(address, ', ', 2) as address_bldgno
from table;
By adding another column to the select I get all the values of that column back, and the split_part() results where they exist.

TSQL - CONCAT_NULL_YIELDS_NULL ON Not Returning Null?

I have had a look around and seem to have come across a strange issue with SQL Server 2008 R2.
I understand that with CONCAT_NULL_YIELDS_NULL = ON means that the following will always resolve to NULL
SELECT NULL + 'My String'
I'm happy with that, however when using this in conjunction with COALESCE() it doesn’t appear to be working on my database.
Consider the following query where MyString is VARCHAR(2000)
SELECT COALESCE(MyString + ', ', '') FROM MyTableOfValues
Now in my query, when MyString IS NULL it returns an empty (NOT NULL) string. I can see this in the query results window.
However unusually enough, when running this in conjunction with an INSERT it fails to recognise the CONCAT_NULL_YIELDS_NULL instead, inserting a blank ‘, ‘.
Query is as follows for insert.
CONCAT_NULL_YIELDS_NULL ON
INSERT INTO Mytable(StringValue)
SELECT COALESCE(MyString + ', ', '')
FROM MyTableOfValues
Further to this I have also checked the database and CONCAT_NULL_YIELDS_NULL = TRUE…
Use NULLIF(MyString, '') instead of just MyString:
SELECT COALESCE(NULLIF(MyString, '') + ', ', '') FROM MyTableOfValues
Coalesce returns the first nonnull expression among its arguments.
You're getting a ', ' because it's the first nonnull expression in your coalesce call.
http://msdn.microsoft.com/en-us/library/ms190349.aspx
From some of the answers provided I was able to assertain a more in depth understanding of COALESCE().
The reason the above query did not fully work was because although I was checking for nulls, and empty string ('') is not considered null. Therefore although the above query worked, I should have checked for empty strings in my table first.
e.g.
SELECT COALESCE(FirstName + ', ', '') + Surname
FROM
(
SELECT 'Joe' AS Firstname, 'Bloggs' AS Surname UNION ALL
SELECT NULL, 'Jones' UNION ALL
SELECT '', 'Jones' UNION ALL
SELECT 'Bob', 'Tielly'
) AS [MyTable]
Will return
FullName
-----------
Joe, Bloggs
Jones
, Jones
Bob, Tielly
Now row 3 has returned a "," character which I was not originally expecting due to a Blank but NOT NULL value.
The following code now works as expected as it checks for blank values. It works, but it looks like I took the long way around. There may be a better way.
-- Ammended Query
SELECT COALESCE(REPLACE(FirstName, Firstname , Firstname + ', '), '') + Surname AS FullName0
FROM
(
SELECT 'Joe' AS Firstname, 'Bloggs' AS Surname UNION ALL
SELECT NULL, 'Jones' UNION ALL
SELECT '', 'Jones' UNION ALL
SELECT 'Bob', 'Tielly'
) AS [MyTable]

Sum like operation for strings in t-sql

I already have query to concatenate
DECLARE #ids VARCHAR(8000)
SELECT #ids = COALESCE(#ids + ', ', '') + concatenatedid
FROM #HH
but if I have to do it inline how can I do that? Any help please.
SELECT sum(quantity), COALESCE(#ids + ', ', '') + concatenatedid from #HH
Thanks.
Use the XML PATH trick. You may need a CAST
SELECT
SUBSTRING(
(
SELECT
',' + concatenatedid
FROM
#HH
FOR XML PATH ('')
)
, 2, 7999)
Also:
Join characters using SET BASED APPROACH (Sql Server 2005)
Subquery returned more than 1 value