Technical Article

Gen. vars, types and select into vars for a table

,

Generates a declare statement including data types for a table and generates a select statement to set the variables from the table.  Speeds development time when dealing with getting values into variable from large tables.

CREATE FUNCTION dbo.fn_cols_to_vars (@table varchar(100)) RETURNS varchar(8000)
AS
BEGIN

/*
Function Name:fn_cols_to_vars
Created By:Joshua J. Beck
Create Date:20021205
Description:Generates a declare statement including data types
for a table and generates a select statement to set
the variables from the table.  Speeds development
time when dealing with large tables.
Use:select dbo.fn_cols_to_vars('con_m1')

Revision History:
WHO|WHEN|WHAT
--------------------------------------------------------------------------
JJB20021205Created

*/declare @col_str varchar(1000), @var_str varchar(1000), @sql_str varchar(1000), @dec_str varchar(7000)

select @dec_str = 'declare'

select @dec_str = @dec_str + '@' + column_name + ' ' + data_type + case when data_type in ('char', 'varchar') 
then '(' + cast(character_maximum_length as varchar(5)) + '), ' + char(13)
else ', ' + char(13)
end
from information_schema.columns 
where table_name = @table
order by ordinal_position

select @col_str = ''

select @col_str = @col_str + column_name + ', '
from information_schema.columns 
where table_name = @table
order by ordinal_position

select @var_str = ''

select @var_str = @var_str + '@' + column_name + ' = t1.' + column_name + ', '
from information_schema.columns 
where table_name = @table
order by ordinal_position

if @@rowcount < 1
begin
select @sql_str = 'table not found'
end
else
begin
select @dec_str = left(@dec_str, datalength(@dec_str) - 3) + char(13)
select @col_str = left(@col_str, datalength(@col_str) - 2)
select @var_str = left(@var_str, datalength(@var_str) - 2)

select @sql_str = 'select ' + @var_str + ' ' + char(13) + 'from ' + @table + ' t1' 
end

return @dec_str + char(13) + char(13) + @sql_str

END

GO

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating