May 8, 2009 at 7:18 am
I have a flattened out data mart table like:
Id int
Name varchar
Address varchar
....
ServiceNumber001Volume int
ServiceNumber002Volume int
ServiceNumber003Volume int
.....
ServiceNumbernnnVolume int
Id like to write something like
pseudo code:
Select all records from myTable where any column name like 'ServiceNumber%' and any of those columns' values are greater than zero.
May 8, 2009 at 7:33 am
you'd have to use dynamic sql to build the sql; here's a working example:
Create Table MyTable(
Id int,
Name varchar,
Address varchar,
ServiceNumber001Volume int,
ServiceNumber002Volume int,
ServiceNumber003Volume int )
declare @sql varchar(max),
@columnsToCheck varchar(max)
SET @columnsToCheck=' WHERE 1 = 1 ' + CHAR(13)
SELECT @columnsToCheck = @columnsToCheck + ' AND ' + syscolumns.name + ' > 0 ' + CHAR(13)
FROM syscolumns
where object_name(id) = 'MyTable'
and name like 'ServiceNumber%'
and type_name(xtype) = 'int'
SELECT @sql = 'SELECT * from MyTable ' + @columnsToCheck
print @sql
--results:
SELECT * from MyTable WHERE 1 = 1
AND ServiceNumber001Volume > 0
AND ServiceNumber002Volume > 0
AND ServiceNumber003Volume > 0
--exec(@sql)
Lowell
May 8, 2009 at 7:40 am
wow, thanks. It works like a charm!
May 8, 2009 at 7:50 am
you probably want to change it to test for OR instead of AND...so it builds like this
SELECT * from MyTable WHERE 1 = 2 --never happens
OR ServiceNumber001Volume > 0
OR ServiceNumber002Volume > 0
OR ServiceNumber003Volume > 0
Lowell
May 8, 2009 at 7:54 am
You may need to read about Normalization
Failing to plan is Planning to fail
May 8, 2009 at 8:07 am
Normalization is awesome! But considering this is a 'flattened' out table for a 'reporting' data mart it was deemed necessary for 'denormalize' the information for performance reasons. Thanks for the tip!
May 8, 2009 at 8:08 am
Lowell, thanks for the 'Or' thing, I changed it a bit and now I'm getting what I need.
May 8, 2009 at 3:47 pm
John (5/8/2009)
Normalization is awesome! But considering this is a 'flattened' out table for a 'reporting' data mart it was deemed necessary for 'denormalize' the information for performance reasons. Thanks for the tip!
Denormalize data for performance reasons???
It's like adding load to speed a car up.
Denormalization adds performance to copy-paste programming, nothing else.
_____________
Code for TallyGenerator
Viewing 8 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply