Last active
December 12, 2015 09:19
-
-
Save doug-wade/4750560 to your computer and use it in GitHub Desktop.
Gets the full domain of an attribute from a relation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if exists | |
( | |
select * | |
from sys.objects | |
where object_id = OBJECT_ID(N'[dbo].[getAttributeDomain]') | |
) | |
begin | |
drop procedure dbo.getAttributeDomain | |
end | |
go | |
create procedure dbo.getAttributeDomain | |
@table varchar(max), | |
@column varchar(max), | |
@outputString varchar(max) OUTPUT | |
as | |
/* Here's what's up | |
Written By: Doug Wade | |
On: 2013-03-04 | |
Does: gets a comma-delimited string of all distinct values in a column. | |
*/ | |
if OBJECT_ID(@table) is null or @column = '' | |
begin | |
return | |
end | |
declare @statement nvarchar(max) = N'select distinct ' + cast(@column as nvarchar) + N' from ' + cast(@table as nvarchar) | |
declare @concatTable table | |
( | |
valueToConcatenate varchar(max) | |
) | |
insert into @concatTable | |
execute sp_executesql @statement | |
declare @counter int = 0 | |
declare attributeCursor cursor | |
for | |
select valueToConcatenate | |
from @concatTable | |
declare @nextAttributeValue varchar(max) | |
open attributeCursor | |
fetch next from attributeCursor into @nextAttributeValue | |
while (@@FETCH_STATUS <> -1) --cursor has reached the end of the array | |
begin | |
if @counter = 0 | |
begin | |
set @outputString = @nextAttributeValue | |
end | |
else | |
begin | |
set @outputString = @outputString + ',' + @nextAttributeValue | |
end | |
set @counter = @counter+1 | |
fetch next from attributeCursor into @nextAttributeValue | |
end | |
close attributeCursor | |
deallocate attributeCursor |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment