?
Solved

Using select and if statements MS SQL Function

Posted on 2011-02-17
2
Medium Priority
?
465 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 2000 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

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

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

This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
This post looks at MongoDB and MySQL, and covers high-level MongoDB strengths, weaknesses, features, and uses from the perspective of an SQL user.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
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…
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