最近因为工作需要,自己写了一个存储过程将数据库中的数据导出至CSV格式。在此记录下来以后使用。
CREATE PROCEDURE [dbo].[Name of Stored procedure]
@DBName as varchar(100),
@TableName as varchar(100),
@ExportFilePath as varchar(500),
@RecordNum as varchar(100)
AS
BEGIN
SET NOCOUNT ON;
Declare @SQLStr varchar(1000)
Declare @Count varchar(100)
If ISNUMERIC(@RecordNum)= 1
SET @Count = 'Top ' + @RecordNum + ' *'
Else
SET @Count = '*'
SET @SQLStr = 'bcp "select ' + @Count + ' from ' + @DBName + '.dbo.' + @TableName + '" queryout "' + @ExportFilePath + '" -T -c -t,'
exec sp_configure 'show advanced options', 1
reconfigure
exec sp_configure 'xp_cmdshell', 1
reconfigure
exec xp_cmdshell @SQLStr
exec sp_configure 'show advanced options', 1
reconfigure
exec sp_configure 'xp_cmdshell', 0
reconfigure
END