1

I have an sql server table with an int column named [type] which is nullable. I have following stored procedure which gets type as input:

    @Jobtype VARCHAR(50) = '',  
    @Language INT
AS
BEGIN
    SELECT [TabId]      
      ,CASE
            WHEN @Language = 2 THEN [TabNameTextLang2]
            ELSE [TabNameTextLang1]
        END AS TabName
      ,CASE
            WHEN @Language = 2 THEN [PageTitleLang2]
            ELSE [PageTitleLang1]
        END AS PageTitle
      ,[TabLink]
      ,[Type]
      ,[Priority]
      ,[DutyStationId]
      ,[DateCreated]
      ,[DateModified]
      ,[Deleted]
    FROM dbo.hr_Tabs
    WHERE Deleted = 0 AND 
    ((@Jobtype = '' and [Type] is null) or  ([Type] = CASt(@Jobtype as int )))

END

this table has a row where type is null. I want that when i pass @jobtype as '' then only that row is selected otherwise rows are shown by their type. But when I try to pass above stored procedure parameters like

exec myproce '', 1

I get all records

Please suggest how to filter records based on type in my case

2
  • 1
    Do you get all rows, or just all rows where type is 0? CAST('' as int) produces a 0, so the second part of the condition could be true. Commented Nov 4, 2013 at 9:55
  • all rows where type is 0 or null Commented Nov 4, 2013 at 9:56

2 Answers 2

2

Use:

((@Jobtype = '' and [Type] is null) or
 (@Jobtype <> '' and [Type] = CAST(@Jobtype as int )))

(I would also generally suggest to use NULL rather than an empty string as your special marker value)

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

1 Comment

in that case I will use following ? ((@Jobtype is null and [Type] is null) or (@Jobtype is not null and [Type] = @Jobtype))
-1

Alternative

FROM dbo.hr_Tabs
CROSS APPLY (select [Type] as dummy intersect select nullif(@Jobtype, '')) x
WHERE Deleted = 0

In order to get an exact match to mr. Smith's answer (logic is the same):

FROM dbo.hr_Tabs
WHERE Deleted = 0 and exists 
(select [Type] as dummy intersect select nullif(@Jobtype, ''))

2 Comments

Normal procedure is to comment when downvoting. This syntax is valid
I was inspired by this answer by @MartinSmith

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.