Wednesday, March 21, 2012

CREATE script that filters out empty columns

All:
Say I need to duplicate a table, but the CREATE script must only
include those columns of the table where the value in ALL the available
rows is not null. For an ad-hoc exercise (one or two tables), this is
easy, but for duplicating, say, 90 tables with the empty columns
filtered out, I assume I need an SP that uses each table's metadata to
test each column individually, for each table. A temp table could then
keep the name of those non-empty columns, and the script would
recreate the new table's script from the resulting set.
If someone can suggest a script to do this, I'll be more than happy...BTW, I do know that information_schema.columns is involved... I know
what the logic should be, I simply don't know how to translate that
logic into T-SQL well enough to be efficient... and maybe VB.NET should
be involved, instead should be something like:
(code to write the beginning of the CREATE TABLE statement, plus the
first bracket)
For all tables in the database
For each column in current_table
SELECT DISTINCT (current_column) , COUNT(*) FROM current_table
GROUP BY (current_column)
If (COUNT(*) >= 1 AND (individual value in the column) <> NULL
then /* This implies that the only value there is not NULL */
(write the name of current_column to a file, plus its data
type and width, and a
comma if not the last column)
end if
next column
next table
(write the closing bracket)
Any suggestions?

No comments:

Post a Comment