I have several tables in a database. I would like to find which columns (in which tables) don't have any values (all NULL in a column). I the example below, the result should be
TestTable1 --> Var2
TestTable2 --> Variable1
I don't have any idea how to create this kind of query. Your help is most appreciated!
--create first table
create table dbo.TestTable1 (
sur_id int identity(1,1) not null primary key,
var1 int null,
var2 int null
)
go
--insert some values
insert into dbo.TestTable1 (var1)
select 1 union all select 2 union all select 3
--create second table
create table dbo.TestTable2 (
sur_id int identity(1,1) not null primary key,
variable1 int null,
variable2 int null
)
--and insert some values
insert into dbo.TestTable2 (variable2)
select 1 union all select 2 union all select 3
For a single column, count(ColumnName)
returns the number of rows where ColumName
is not null:
select count(TheColumn)
from YourTable
You can generate a query for all columns. Per Martin's suggestion, you can exclude columns that cannot be null with is_nullable = 1
. For example:
select 'count(' + name + ') as ' + name + ', '
from sys.columns
where object_id = object_id('YourTable')
and is_nullable = 1
If the number of tables is large, you can generate a query for all tables in a similiar way. The list of all tables is in sys.tables
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With