Concat two column in a select statement sql server 2005 - sql-server-2005

How to Concat two column in a select statement sql server 2005?
Here is my statement Select FirstName,secondName from Table...
Now i did try concating secondName with FirstName by using
Select FirstName + ' ' + secondName from Table
But some values are NULL in secondName column for some records.. My select statement
returns NULL instead of FirstName.. I want to have FirstName if secondName is NULL ..

SELECT FirstName + ISNULL(' ' + SecondName, '') from Table

If one of your fields is numeric then you can cast it to a string as follows:
SELECT FirstName + ISNULL(' ' + SecondName, '') + ' age(' + CONVERT(nvarchar,age) + ')' from Table

do like this :
select cast( FirstName as varchar)+' '+cast( secondName as varchar) from table

Related

Text + Text when a value is NULL (SQL) [duplicate]

This question already has answers here:
SQL Server String Concatenation with Null
(10 answers)
Closed 1 year ago.
I have a problem in SQL Server. I have a query
select FirstName, + ", " + LastName as FullName
If LastName = NULL and FirstName = "Fred"
Then FullName would be NULL. Is there a way to just have the FirstName instead?
Here is what I get: https://i.stack.imgur.com/NbLWL.png
I would go with
Select Case
When LastName Is Null
Then FirstName
Else Concat(FirstName, ", ", LastName)
End As FullName
Since SQL Server 2017, you can use concat_ws():
select concat_ws(', ', firstname, lastname)
In earlier versions, you can use:
select stuff( concat(', ' + firstname,
', ' + lastname
), 1, 2, ''
)
In addition to concat function, if you are having very old sql server version, you can use ISNULL to fill up empty string in place of null value.
select
CASE WHEN LastName IS NOT NULL
THEN ISNULL(FirstName,'') + ", " + LastName
ELSE ISNULL(FirstName,'') END as FullName

How can I store a SELECT query result(one column) into a new table's column?

This is my query:-
select
(FirstName + ' ' + Lastname) as [Name]
from
c_client
where
MiddleInitial is null
union
select
(FirstName + ' ' + MiddleInitial + '''' + Lastname) as [Name]
from
c_client
where
MiddleInitial is not null
After executing it, I'm getting this output:
This is my new table:
CREATE TABLE AddData(Name VARCHAR(MAX))
I want to insert the result generated by the SELECT query into my new table AddData. Can you help me do this?
You would use insert:
insert into AddData (Name)
Select (FirstName + ' ' + Lastname) as [Name]
from c_client
where MiddleInitial IS NULL
UNION
Select (FirstName + ' ' + MiddleInitial +''''+ Lastname) as [Name]
from c_client
where MiddleInitial IS NOT NULL;
I would instead suggest writing the logic as :
select (FirstName +
coalesce(MiddleInitial + '''', '') +
' ' +
Lastname
) as Name
into AddData
from c_client c;
You won't have to create the table first.
Also, if you do want to remove duplicates then use select distinct. It is not clear if you are using union intentionally to remove duplicates or just to combine two separate subqueries.

How to join two SQL queries?

Making two SQL queries into the same table
SELECT FirstName,
LastName,
LEFT(FirstName, 1) + '.' + LEFT(LastName, 1) AS Initial
FROM ContactUpdates
This outputs:
FirstName LastName Initial
I want this to join this other one on the right side where Initial ends
SELECT LOWER(LEFT(FirstName, 1) + REPLACE(LastName,'''','' ) )
+ '#email.com' AS Email
FROM ContactUpdates
In the end I want it to be
FirstName LastName Initial Email
But I can't figure out how to make them join any help?
SELECT FirstName,
LastName,
LEFT(FirstName,1) + '.' + LEFT(LastName,1) AS Initial,
LOWER(LEFT(FirstName, 1) + REPLACE(LastName, '''', '')) + '#email.com' AS Email
FROM ContactUpdates
Then simply append that column to the query:
SELECT FirstName
, LastName
, LEFT(FirstName,1) + '.' + LEFT(LastName,1) AS Initial
, LOWER(LEFT(FirstName,1) + REPLACE(LastName,'''','' ) ) + '#email.com' AS Email
FROM ContactUpdates

How to convert two nvarchar rows into one when one of the row is null

sorry if this is a duplicate to one of existing questions (it's so simple but I can't figure it out, I'm new).
I need to migrate some data from one table to another (different structures).
Table A have Firstname and LastName columns.
Table B have Name column
I want to do
SELECT Firstname + ' ' + LastName As Name FROM TableA
But the problem is that in table B, some rows have null value for firstname or lastname but not both (Lazy user).
When I import them into table B, the query fails because Name column is non-nullable in my new design and when I test the statement above, if firstname or lastname is null, the concated value is null.
From the reading that I've done, this is expected behavior but what can I do to get around this?
I want to save firstname or lastname if the other is null.
SELECT RTRIM(LTRIM(ISNULL(Firstname ,'') + ' ' + ISNULL(LastName,''))) AS Name
FROM TableA
This can be done with a single colaesce (return first non-null) & no need to mess about with spaces.
select
coalesce(firstname + ' ' + lastname, firstname, lastname)
from TableA
use coalesce or isnull
select COALESCE(FirstNAme, '') + ' ' + COALESCE(LastName, '') as name from TableA
SELECT isnull (Firstname, '') + ' ' isnull (LastName, '') as Name
FROM TableA

How do I perform a GROUP BY on an aliased column in SQL Server?

I'm trying to perform a group by action on an aliased column (example below) but can't determine the proper syntax.
SELECT LastName + ', ' + FirstName AS 'FullName'
FROM customers
GROUP BY 'FullName'
What is the correct syntax?
Extending the question further (I had not expected the answers I had received) would the solution still apply for a CASEed aliased column?
SELECT
CASE
WHEN LastName IS NULL THEN FirstName
WHEN LastName IS NOT NULL THEN LastName + ', ' + FirstName
END AS 'FullName'
FROM customers
GROUP BY
LastName, FirstName
And the answer is yes it does still apply.
You pass the expression you want to group by rather than the alias
SELECT LastName + ', ' + FirstName AS 'FullName'
FROM customers
GROUP BY LastName + ', ' + FirstName
This is what I do.
SELECT FullName
FROM
(
SELECT LastName + ', ' + FirstName AS FullName
FROM customers
) as sub
GROUP BY FullName
This technique applies in a straightforward way to your "edit" scenario:
SELECT FullName
FROM
(
SELECT
CASE
WHEN LastName IS NULL THEN FirstName
WHEN LastName IS NOT NULL THEN LastName + ', ' + FirstName
END AS FullName
FROM customers
) as sub
GROUP BY FullName
Unfortunately you can't reference your alias in the GROUP BY statement, you'll have to write the logic again, amazing as that seems.
SELECT LastName + ', ' + FirstName AS 'FullName'
FROM customers
GROUP BY LastName + ', ' + FirstName
Alternately you could put the select into a subselect or common table expression, after which you could group on the column name (no longer an alias.)
Sorry, this is not possible with MS SQL Server (possible though with PostgreSQL):
select lastname + ', ' + firstname as fullname
from person
group by fullname
Otherwise just use this:
select x.fullname
from
(
select lastname + ', ' + firstname as fullname
from person
) as x
group by x.fullname
Or this:
select lastname + ', ' + firstname as fullname
from person
group by lastname, firstname -- no need to put the ', '
The above query is faster, groups the fields first, then compute those fields.
The following query is slower (it tries to compute first the select expression, then it groups the records based on that computation).
select lastname + ', ' + firstname as fullname
from person
group by lastname + ', ' + firstname
Given your edited problem description, I'd suggest using COALESCE() instead of that unwieldy CASE expression:
SELECT FullName
FROM (
SELECT COALESCE(LastName+', '+FirstName, FirstName) AS FullName
FROM customers
) c
GROUP BY FullName;
My guess is:
SELECT LastName + ', ' + FirstName AS 'FullName'
FROM customers
GROUP BY LastName + ', ' + FirstName
Oracle has a similar limitation, which is annoying. I'm curious if there exists a better solution.
To answer the second half of the question, this limitation applies to more complex expressions such as your case statement as well. The best suggestion I've seen it to use a sub-select to name the complex expression.
You can use CROSS APPLY to create an alias and use it in the GROUP BY clause, like so:
SELECT FullName
FROM Customers
CROSS APPLY (SELECT LastName + ', ' + FirstName AS FullName) Alias
GROUP BY FullName
SELECT
CASE
WHEN LastName IS NULL THEN FirstName
WHEN LastName IS NOT NULL THEN LastName + ', ' + FirstName
END AS 'FullName'
FROM
customers
GROUP BY
LastName,
FirstName
This works because the formula you use (the CASE statement) can never give the same answer for two different inputs.
This is not the case if you used something like:
LEFT(FirstName, 1) + ' ' + LastName
In such a case "James Taylor" and "John Taylor" would both result in "J Taylor".
If you wanted your output to have "J Taylor" twice (one for each person):
GROUP BY LastName, FirstName
If, however, you wanted just one row of "J Taylor" you'd want:
GROUP BY LastName, LEFT(FirstName, 1)
If you want to avoid the mess of the case statement being in your query twice, you may want to place it in a User-Defined-Function.
Sorry, but SQL Server would not render the dataset before the Group By clause so the column alias is not available. You could use it in the Order By.
In the old FoxPro (I haven't used it since version 2.5), you could write something like this:
SELECT LastName + ', ' + FirstName AS 'FullName', Birthday, Title
FROM customers
GROUP BY 1,3,2
I really liked that syntax. Why isn't it implemented anywhere else? It's a nice shortcut, but I assume it causes other problems?
SELECT
CASE WHEN LastName IS NULL THEN FirstName
WHEN LastName IS NOT NULL THEN LastName + ', ' + FirstName
END AS 'FullName'
FROM customers GROUP BY 1`
For anyone who finds themselves with the following problem (grouping by ensuring zero and null values are treated as equals)...
SELECT AccountNumber, Amount AS MyAlias
FROM Transactions
GROUP BY AccountNumber, ISNULL(Amount, 0)
(I.e. SQL Server complains that you haven't included the field Amount in your Group By or aggregate function)
...remember to place the exact same function in your SELECT...
SELECT AccountNumber, ISNULL(Amount, 0) AS MyAlias
FROM Transactions
GROUP BY AccountNumber, ISNULL(Amount, 0)