Solved

SQL Server - conditional statement in the select list

Posted on 2011-03-10
3
437 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 40

Expert Comment

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

Open in new window

0
 
LVL 40

Accepted Solution

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

Open in new window

0
 
LVL 32

Expert Comment

by:ewangoya
ID: 35101482

declare @SQL

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

--print @SQL
0

Featured Post

Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

Question has a verified solution.

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

Suggested Solutions

Composite queries are used to retrieve the results from joining multiple queries after applying any filters. UNION, INTERSECT, MINUS, and UNION ALL are some of the operators used to get certain desired results.​
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

838 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