Skip to content

Instantly share code, notes, and snippets.

@zikani03
Last active December 18, 2015 04:49
Show Gist options
  • Save zikani03/5728141 to your computer and use it in GitHub Desktop.
Save zikani03/5728141 to your computer and use it in GitHub Desktop.
I was looking for a way to create a csv record of a row so i could use in a query.
-- @name row_to_csv
-- @descr create a csv record of any row from any table in MSSQL 2005+
-- @param table_name : full schema qualified name e.g. [dbo].[companies]
-- @param conditions select conditions .e.g "WHERE companies.company_id = 50
CREATE FUNCTION dbo.row_to_csv( @table_name as varchar(100) , @conditions as varchar(200))
returns varchar(2048)
AS
begin
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''+@table_name) AND type in (N'U'))
RETURN 'SELECT ''ERROR: TABLE ' + CHAR(40) + @table_name + CHAR(41) +' DOES NOT EXIST''';
declare @q varchar(2048);
declare @col_cache varchar(2048);
declare @table_columns table(row_num tinyint identity, column_name varchar(100));
declare @comma_space_literal varchar(50);
declare @number_of_columns tinyint;
set @comma_space_literal = ' + SPACE(1) + CHAR(44) + ';
insert into @table_columns
SELECT [name] FROM sys.all_columns where object_id = OBJECT_ID(N''+@table_name) order by column_id;
set @number_of_columns = (select count(*) from @table_columns);
set @col_cache = SPACE(1);
declare @current_row tinyint; set @current_row = 1;
declare @cast_wrapper varchar(150);
set @cast_wrapper = 'CHAR(34) + cast([{0}] AS varchar(200)) + CHAR(34)';
while (@number_of_columns >= @current_row)
begin
-- we get prevColumn + ', ' + columnName for each column
set @col_cache = @col_cache + @comma_space_literal + Replace(@cast_wrapper,'{0}',(select column_name from @table_columns where row_num = @current_row))
set @current_row = @current_row + 1
end
-- the col_cache will be like this at this point
-- + ', ' + column1 + ', ' + column2 ... + ', ' + columnN
set @q = 'SELECT TOP(1) {0} FROM ' + @table_name ;
-- remove leading SPACE(1) + CHAR(44)
set @col_cache = Substring(@col_cache,len(@comma_space_literal)+ 2,len(@col_cache));
set @q = Replace(@q,'{0}',@col_cache);
-- add the conditions, if they exist
if (len(@conditions) > 0)
set @q = @q + SPACE(1) + @conditions
RETURN @q
end
-- example of calling the function
declare @query varchar(max);
declare @tab table(record varchar(2048));
set @query = dbo.row_to_csv_tpl('[dbo].[Companies]','Where company_id > 5');
INSERT INTO @tab exec sp_sqlexec @query;
select top(1) * from @tab;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment