I have 70 plus tables from my database. I can get the list of all tables by using sys.tables with specific column name. I should get the null values of that specific column for all tables from my database. I am new to SQL. Can anyone please guide me on this. I got the list of tables by using the below query.
SELECT OBJECT_SCHEMA_NAME (c.object_id) SchemaName,
o.Name AS Table_Name,
c.Name AS Field_Name,
t.Name AS Data_Type,
t.max_length AS Length_Size,
t.precision AS Precision
FROM sys.columns c
INNER JOIN sys.objects o ON o.object_id = c.object_id
LEFT JOIN sys.types t on t.user_type_id = c.user_type_id
WHERE o.type = 'U'
-- and o.Name = 'YourTableName'
ORDER BY o.Name, c.Name
try this for starters and see what is inside that #kampataboo table. All tables might not have the same custom defined tables and same column data type. so this could ugly very fast or might end up in kludgy solution. What is the end goal here? Just find null values?
Notice I started out with @columnName varchar(150) = 'vmid'; In there plug a column that you know could be null just to give this a start and post back here.
use yourDatabase
go
declare @findNullQuery varchar(max), @parmtableName varchar(150),
@parmcolumnName varchar(150),
@tableName varchar(150), @columnName varchar(150) = 'vmid';
create table #kampataboo(tablename varchar(150), columnname varchar(150), query varchar(max));
DECLARE db_cursor CURSOR FOR
select t.name, c.name, 'select ''' + t.name + ''' as tablename, ''' + c.name + ''' as columnname from ' + t.name + ' where ' + c.name + ' is null '
from sys.tables t
join sys.columns c on t.object_id = c.object_id
where ( @columnName is null or c.name = @columnName )
and ( @tableName is null or t.name = @tableName )
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @tableName , @columnName, @findNullQuery
WHILE @@FETCH_STATUS = 0
BEGIN
--select @findNullQuery
insert into #kampataboo
select @tableName, @columnName, @findNullQuery
FETCH NEXT FROM db_cursor INTO @tableName , @columnName, @findNullQuery
END
CLOSE db_cursor
DEALLOCATE db_cursor
select * From #kampataboo
drop table #kampataboo
So, as per your answer, you're creating a temporary table ans storing those values into that table. Once, we displayed the results, you're dropping that table. am I right?
Just add
Insert into forensics
Exec(@findNullQuery)
But remember different tables might have different data type for same column so you need convert to a common data type of make destination column be nvarchar(max)