Solved

Using select and if statements MS SQL Function

Posted on 2011-02-17
2
458 Views
Last Modified: 2012-06-27
Hi,

I have the following funciton working fine although I want to modify it so that it runs a select statement first that checks if the Builder's status is awarded.  

From there I want to have an if statement to run either the below select statment or a differnet one based on whether or not hte builder is awarded.

Any ideas?
ALTER FUNCTION [dbo].[fnBuildersByProject]
      (@ProjectID int , @PID int  )
RETURNS varchar(1000) 
AS
BEGIN
declare @List varchar(1000)

SELECT            @List = COALESCE(@List + ', ', '') + ltrim(rtrim(convert(varchar,BuilderCompany)))
FROM      Builders
WHERE       Builders.projectID = @ProjectID
ORDER BY   Builders.BuilderCompany

RETURN @List

 

END

Open in new window

0
Comment
Question by:glit
2 Comments
 
LVL 75

Accepted Solution

by:
Anthony Perkins earned 500 total points
ID: 34923203
Something like this:
ALTER FUNCTION [dbo].[fnBuildersByProject]
    (@ProjectID int,
     @PID int)
RETURNS varchar(1000)
AS 
BEGIN
    DECLARE @List varchar(1000)

	IF EXISTS (
		SELECT 1
		FROM   YourTable
		WHERE  BuilderStatus = 1
		)
		SELECT  @List = COALESCE(@List + ', ', '') + LTRIM(RTRIM(CONVERT(varchar, BuilderCompany)))
		FROM    Builders
		WHERE   Builders.projectID = @ProjectID
		ORDER BY Builders.BuilderCompany
	ELSE
		SELECT ...
		FROM ...
		WHERE ...
	
    RETURN @List

 

END

Open in new window

0
 

Author Closing Comment

by:glit
ID: 34923236
That's perfect, thank you!
0

Featured Post

Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

Question has a verified solution.

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

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
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 the fundamental information of how to create a table.

867 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now