SQL Server Is there a quick way to check if ANY column is NULL?

iklwldmw  于 2023-04-28  发布在  其他
关注(0)|答案(5)|浏览(141)

I have a table with around 20 columns. Aside from typing out:

Where column1 is null OR column2 is null OR column3 is null etc...

Is there a quicker way to just check every column and see if any value is null and if so, return that record?

ecfsfe2w

ecfsfe2w1#

No. There are ways to code it quicker, but there are no shortcuts like you imply. Taken from an answer I gave on dba.stackexchange :

DECLARE @tb NVARCHAR(255), @sql NVARCHAR(MAX);

SET @tb = N'dbo.[table]';

SET @sql = N'SELECT * FROM ' + @tb + ' WHERE 1 = 0';

SELECT @sql = @sql + N' OR ' + QUOTENAME(name) + ' IS NULL'
    FROM sys.columns 
    WHERE [object_id] = OBJECT_ID(@tb);

EXEC sp_executesql @sql;
d7v8vwbk

d7v8vwbk2#

You can find the column names using something like this:

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = <table_name>

Then, I would write a procedure using this, and that would loop through the entries in your table and the column names.

Source: http://codesnippets.joyent.com/posts/show/337

nzk0hqpo

nzk0hqpo3#

That depends on what quicker means.

If you mean quicker for SQL Server to execute, one thing you could do is write a trigger than updates a bit column that specifies if the entire row (other than the bit and primary key) are NULL. But, there should be a REAL good reason for this as it will impact your update performance. Indexes on those columns would help as well.

If you mean quicker to write, you could have SQL generate the where clause for you. But, unless you do this alot, it isn't worth the time in my opinion.

4ktjp1zp

4ktjp1zp4#

Teaching-to-fish-instead-of-giving-you-the-fish kind of answer here:

One way of doing it is by creating a Stored Procedure that assembles and runs a dynamic query.

The Stored procedure will:

  • have a Table name as input parameter.
  • query the meta data system tables for the specific table structure.
  • dynamically assemble a string (the actual query) with the OR statements for that table's columns.
  • run the assembled query and return the result.
sd2nnvve

sd2nnvve5#

You can check by doing case and sum like this:

SELECT 
(case when (sum(case when id is null then 1 else 0 end)) > 0 then True else False end) as is_id_null,
(case when (sum(case when id is null then 1 else 0 end)) > 0 then True else False end) as is_name_null
from TABLE;

相关问题