Billy wrote:
> Yes I am working with data that is not normalized. That doesn't mean
> I don't realize it. I have to work with the data the way it is.
>
> On May 14, 8:00 am, dave ballantyne
> wrote:
>> Billy wrote:
>>> Is there a way to add a where clause to this statement
>>> SELECT * FROM tableName
>>> so that you only return columns that don't have a null in each row?
>>> I don't want blank columns returned......but this will change each
>>> month so I don't want to hard code the column names.
>> Sounds as if you have made a fundemental error in your understanding of
>> relational databases.
>>
>> It sounds as if you table is
>>
>> PKey Int,
>> Month1 int,
>> Month2 int,
>> Month3 int,
>> Month4 int,
>> ....
>> ...
>> ..
>>
>> It Should be
>>
>> PKey Int
>> MonthNum Int
>> MonthValue int
>>
>> And then populated with rows not columns.
>>
>> Dave
>
If i understand you right, this should help. Ive done it as a two pass
operation to avoid multiple scans on the source table, that may or may
not bother you.
Dave
Create Table xxtestt1
(
col1 int null,
col2 int null,
col3 int null,
col4 int null)
insert into xxtestt1 values(Null,1,Null,NULL)
go
drop table xxskeltab
go
declare @colname varchar(20)
declare @SqlString nvarchar(2048)
declare tcursor cursor for
select name from syscolumns
where id = object_id('xxtestt1')
open tcursor
while(0=0) begin
fetch next from tcursor into @Colname
if(@@Fetch_status<>0) break
if @SqlString is null begin
Select @SqlString = 'SELECT '
end else begin
Select @SqlString = @SqlString+','
end
Select @SqlString = @SqlString +@ColName+'= max(case when
'+@Colname+' is not null then 1 else 0 end) '
end
close tcursor
deallocate tcursor
Select @SqlString = @SqlString +' into xxskeltab From xxtestt1'
select @SqlString
EXECUTE sp_executesql @SQLString;
go
Declare @SqlString nvarchar(2048)
declare @FullSql nvarchar(2048)
declare @Colname varchar(20)
declare @Colret integer
declare tcursor cursor for
select name from syscolumns
where id = object_id('xxskeltab')
open tcursor
while(0=0) begin
fetch next from tcursor into @Colname
if(@@Fetch_Status<>0) break
Select @SqlString = 'Select @ColRetout='+@Colname+' from xxskeltab '
exec sp_executesql @SqlString,N'@ColRetout integer
Output',@ColRetout =@ColRet OUTPUT
if(@ColRet=1) begin
if(@Fullsql is null) begin
Select @FullSql = 'Select '
end else begin
Select @FullSql = ','
end
Select @FullSql = @FullSql + @Colname
end
end
close tcursor
deallocate tcursor
select @FullSql = @Fullsql +' from foo'
select @FullSql
>> Stay informed about: select all columns that are not null