0

I want to return if there is a record in my table then return it and if that table haven't a record,then return 'America/Chicago'.

Error: Msg 102, Level 15, State 1, Procedure ufn_GetGCMoodleTimeZone, Line 18 [Batch Start Line 7] Incorrect syntax near '@MoodleTimeZone'. Msg 102, Level 15, State 1, Procedure ufn_GetGCMoodleTimeZone, Line 22 [Batch Start Line 7] Incorrect syntax near 'END'.

ALTER FUNCTION [dbo].[ufn_GetGCMoodleTimeZone]
 ( @HSATimeZone VARCHAR(250) )RETURNS varchar(250)
AS
  BEGIN
    DECLARE @MoodleTimeZone varchar(250) 
    SELECT @MoodleTimeZone = GCMoodleTimeZoneMap.MoodleTimeZone
    FROM GCMoodleTimeZoneMap
    WHERE GCMoodleTimeZoneMap.HSATimeZone = @HSATimeZone
    IF @MoodleTimeZone='NULL'
    BEGIN
            @MoodleTimeZone='America/Chicago'
    END 
    RETURN @MoodleTimeZone

  END

1
  • 1
    @MoodleTimeZone='America/Chicago' --> SET @MoodleTimeZone='America/Chicago'. Also, @MoodleTimeZone='NULL' should be @MoodleTimeZone IS NULL'. You could easily rewrite this to a table valued function to increase performance (and readability). Commented Jun 19, 2020 at 8:25

1 Answer 1

1

The comment about using SET and how to check for NULL are correct, so I will not repeat that. Still what you want can be written shorter and more efficiently as follows:

ALTER FUNCTION [dbo].[ufn_GetGCMoodleTimeZone]
 ( @HSATimeZone VARCHAR(250) )RETURNS varchar(250)
AS
BEGIN
  RETURN ISNULL(
      (SELECT TOP 1 MoodleTimeZone
       FROM   GCMoodleTimeZoneMap
       WHERE  HSATimeZone = @HSATimeZone
      ), 'America/Chicago'
    )
END

Explanation:

  1. The inner SELECT will return either a single row, or no rows.
  2. The ISNULL() will process that result, and in the "no rows"-case it will substitute the default value 'America/Chicago'.

Here is a working DB Fiddle:
https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=f4c9e946475818e538ed8f63160d6971

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.