我需要创建一个存储过程来查询表,并在指定的目录位置为该数据创建一个CSV文件。
我该怎么办?
答案 0 :(得分:2)
您无法直接使用存储过程执行此操作。我建议在SQL Server Management Studio中右键单击您的数据库,然后选择“导出数据”。
使用返回行的查询或存储过程提供它。告诉它你希望文件用逗号分隔,文本用引号限定。
当向导询问您是要执行还是保存时,请将其保存到磁盘。
这会产生一种称为SSIS包的东西。然后,您可以使用Windows资源管理器运行它,或使用名为dtexec.exe的命令行程序来运行参数,或者将其提供给DBA以让它们在SQL Server中运行。
答案 1 :(得分:1)
您可以通过exec xp_cmdshell调用BCP'bcp dbname..table out filename.bcp .....'
除了导入之外,这是一个非常相似的问题。 Use bcp to import csv file to sql 2005 or 2008
答案 2 :(得分:1)
可以这样做但你需要有足够的权限来运行xp_cmdshell和ad hoc分布式查询。
sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO
sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO
DECLARE @OutputPath VARCHAR(1000)
SET @OutputPath = 'd:\temp\'
DECLARE @OutputFilename VARCHAR(1000)
DECLARE @ServerName VARCHAR(1000)
SET @ServerName='servername'
DECLARE @Username VARCHAR(50)
SET @Username = 'username'
DECLARE @Password VARCHAR(50)
SET @Password = 'password'
DECLARE @DatabaseName VARCHAR(50)
SET @DatabaseName = 'databasename'
DECLARE @Dsn VARCHAR(1000)
SET @Dsn = 'Server='+@ServerName+';Database='+@DatabaseName+';Uid='+@Username+';Pwd='+@Password+';'
DECLARE @StartProcedureTime DATETIME
DECLARE @EndProcedureTime DATETIME
DECLARE @TimeTaken INTEGER
DECLARE @QueryToRun VARCHAR(1000)
DECLARE @Query VARCHAR(1000)
DECLARE @result INT
SET @Query = 'mkdir "' + @OutputPath + @DatabaseName +'\"'
EXEC @result = [master]..xp_cmdshell @Query
DECLARE db_cursor CURSOR FOR
SELECT
T.[FileName] + '.csv' AS [FileName],
REPLACE(T.SqlToRun, '''', '''''') AS [SqlToRun]
FROM
(
SELECT 'sp_DataGenerator_AverageRatingAverage' AS [FileName], 'exec sp_DataGenerator_AverageRatingAverage 54' AS [SqlToRun]
UNION ALL
SELECT 'sp_DataGenerator_AverageRatingGood', 'exec sp_DataGenerator_AverageRatingGood ''01-01-2009'', ''01-01-2010'''
UNION ALL
SELECT 'sp_DataGenerator_AverageRatingBad', 'exec sp_DataGenerator_AverageRatingBad ''01-01-2009'', ''01-01-2010'''
) AS T
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @OutputFilename, @QueryToRun
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Query = 'bcp "SELECT * FROM OPENROWSET (''SQLOLEDB'','''+@Dsn+''','''+@QueryToRun+''') AS T" queryout '+@OutputPath + @DatabaseName + '\' + @OutputFilename +' -c -t, -r\n -U'+@Username+' -P'+@Password+' -S'+@ServerName + ' > ' +@OutputPath + @DatabaseName + '\' + @OutputFilename +'.txt'
SET @StartProcedureTime = getdate() --take start time
EXEC @result = [master]..xp_cmdshell @Query
SET @EndProcedureTime = getdate() --take end time
SET @TimeTaken = DATEDIFF(millisecond, @StartProcedureTime, @EndProcedureTime) --take difference in milliseconds.
PRINT '"'+@QueryToRun + '" took ' + str(@TimeTaken) + ' Milliseconds.'
FETCH NEXT FROM db_cursor INTO @OutputFilename, @QueryToRun
END
CLOSE db_cursor
DEALLOCATE db_cursor
go
sp_configure 'xp_cmdshell', 0
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 0
GO
RECONFIGURE
GO
sp_configure 'Show Advanced Options', 0
GO
RECONFIGURE
GO