?
Solved

SQL Server - conditional statement in the select list

Posted on 2011-03-10
3
Medium Priority
?
446 Views
Last Modified: 2012-06-21
I have a query that needs to build a display name for a field as part of the select list.  The display name will consist of two database fields from the tables in the query.  The first field will always be displayed.  But the second field could potentially be null.  If the second field is null then I just want to display the first field.  But if the second field is not null then I want to display the first field a colon and then the second field and have it returned as part of the select list.

Thanks
0
Comment
Question by:JosephEricDavis
  • 2
3 Comments
 
LVL 41

Expert Comment

by:Sharath
ID: 35101081
Try like this.
select FirstField,COALESCE(FirstField+':'+SecondField,FirstField) SecondField

Open in new window

0
 
LVL 41

Accepted Solution

by:
Sharath earned 2000 total points
ID: 35101083
or this.
select FirstField,ISNULL(FirstField+':'+SecondField,FirstField) AS SecondField

Open in new window

0
 
LVL 32

Expert Comment

by:Ephraim Wangoya
ID: 35101482

declare @SQL

select @SQL = FirstField + ISNULL(',' + SecondField, '')

--print @SQL
0

Featured Post

Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
When trying to connect from SSMS v17.x to a SQL Server Integration Services 2016 instance or previous version, you get the error “Connecting to the Integration Services service on the computer failed with the following error: 'The specified service …
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question