Ish
Ish

Reputation: 671

ISNULL Column SQL

Problem: The code reads each row and should determine whether it is empty or not. I want to print out "works" if the column is null. Otherwise, it should not do anything. Right now it is not working. It is giving me an error that the column does not exist.(the one mentioned in the if statement)

Here is the code. Code:

DECLARE Employee_Cursor CURSOR FOR

SELECT [Description]  
FROM tblSubViews ts  
INNER JOIN tblViewSubViewJoin tvs  
ON ts.SubViewId = tvs.SubViewId Where tvs.ViewId = 4

OPEN Employee_Cursor

FETCH NEXT FROM Employee_Cursor
WHILE @@FETCH_STATUS = 0

BEGIN   
if (Description = null)
begin
print 'works'
end
   FETCH NEXT FROM Employee_Cursor
END
CLOSE Employee_Cursor
DEALLOCATE Employee_Cursor

Upvotes: 0

Views: 320

Answers (4)

Gaurav Agrawal
Gaurav Agrawal

Reputation: 4431

Use the isnull() function in your query, according to your logic.

Upvotes: 0

Purplegoldfish
Purplegoldfish

Reputation: 5284

There isnt a need for a cursor in this situation

SELECT 
[Description],
ISNULL([Description]   ,'Works') AS text
FROM tblSubViews ts   
INNER JOIN 
tblViewSubViewJoin tvs   
ON 
ts.SubViewId = tvs.SubViewId 
Where 
tvs.ViewId = 4

You could then shorten this down by adding an extra criteria to your WHERE clause that only selects null description columns?

Upvotes: 2

marc_s
marc_s

Reputation: 754518

NULL is a special value in SQL - actually, it's the absence of a value.

Therefore, since it's not a value, you cannot compare with regular means - you need to use the IS NULL or IS NOT NULL methods:

if (Description IS NULL)
begin
  print 'works'
end

Comparing with IS NULL or IS NOT NULL will give you the result you're looking for.

Upvotes: 3

faester
faester

Reputation: 15076

You cannot compare to NULL using equals, you mush use ID (Description IS NULL)

When using cursors it is also necessary to select into a variable:

  FETCH NEXT FROM Employee_Cursor INTO @Description 
  WHILE @@FETCH_STATUS = 0

You would of course need to declare @Description to be of a type appropriate for the column,

Upvotes: 2

Related Questions