1

in an sql database I need a script that will select all the rows that has no null value something like this:

For all the rows in the database
     if row has no null values
         select it

Columns are dynamic, I cannot know their number or names

Thanks you

1
  • Did you mean a specific table? or the whole database? What kind of "dynamic" are you talking about. Temp tables included? Commented Aug 17, 2012 at 7:21

2 Answers 2

4

This is the opposite of this question Test if any fields are NULL.

The answer by Martin Smith modified to find rows without null values would look like this.

;with xmlnamespaces('http://www.w3.org/2001/XMLSchema-instance' as ns)
select *
from YourTable as T
where
  (
    select T.*
    for xml path('row'), elements xsinil, type 
  ).exist('//*/@ns:nil') = 0

And the answer provided by Aaron Bertrand modified would be...

DECLARE @tb NVARCHAR(255) = N'YourTable';

DECLARE @sql NVARCHAR(MAX) = N'SELECT * FROM ' + @tb
    + ' WHERE 1 = 1';

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

EXEC sp_executesql @sql;
Sign up to request clarification or add additional context in comments.

Comments

-1

Approach:

  • Get column names of a table from sys.columns
  • do the select with multiple WHERE conditions ANDed: WHERE ColA IS NOT NULL AND ColB IS NOT NULL and so on...

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.