-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexport_tbl.sql
More file actions
34 lines (27 loc) · 885 Bytes
/
export_tbl.sql
File metadata and controls
34 lines (27 loc) · 885 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
exec dbo.drop_if_exists '[dbo].[export_tbl]'
GO
create procedure dbo.export_tbl
@tbl_name sysname,
@quote nvarchar(max) = '"',
@escape nvarchar(max) = '""'
as
set nocount on
declare @stmt nvarchar(max) = 'select '''
select @stmt += case row_number() over (order by c.column_id) when 1 then '' else ',' end + dbo.quote_data(c.name, @quote, @escape)
from sys.columns c
where c.object_id = object_id(@tbl_name)
order by c.column_id
set @stmt += ''' as Data
union all
select'
select @stmt += case row_number() over (order by c.column_id) when 1 then '' else ' + '','' + ' end + '
' + 'dbo.quote_data(isnull(cast(' + quotename(c.name) + ' as nvarchar(max)), ''''),''' + @quote + ''',''' + @escape + ''')'
from sys.columns c
where c.object_id = object_id(@tbl_name)
order by c.column_id
set @stmt += '
from ' + @tbl_name
set nocount off
print @stmt
exec sp_executesql @stmt
GO