我有一个存储过程在查询执行后返回路径中的csv输出。但它只适用于单个csv。
我希望脚本能够从多个SQL语句一起生成多个csv并存储在路径中。
我的输入是here
---------------------------------------------
--- Generating output csv by stored procedure
---------------------------------------------
DECLARE @sql NVARCHAR(MAX) = 'SELECT * from #TMP_Lazyone_All_Final'
DECLARE @file_path NVARCHAR(4000) = N'D:\a\Lazyone_ComplexProducts_Final.csv' -- Change filename path
DECLARE @Status INT = 1
EXECUTE spa_util_GetCsv @DBFetch = @sql,
@Header = 1,
@PCWrite = @file_path,
@HeaderQuote = 0,
@Status = @Status OUTPUT
答案 0 :(得分:0)
您可以使用while循环来实现您的需求:
DECLARE @i int = 0
DECLARE @t TABLE (
id int,
querys nvarchar(max),
filename nvarchar(max)
)
DECLARE @sql NVARCHAR(MAX),
@file_path NVARCHAR(4000) = N'D:\a\',
@Status INT = 1
INSERT INTO @t VALUES
(0, 'first query', @file_path+'first'+'.csv'),
(1, 'second query',@file_path+ 'second'+'.csv')
--etc
WHILE @i < (SELECT COUNT(*) FROM @t)
BEGIN
SELECT @sql = querys,
@file_path = filename
FROM @t
WHERE id = @i
EXECUTE spa_util_GetCsv @DBFetch = @sql,
@Header = 1,
@PCWrite = @file_path,
@HeaderQuote = 0,
@Status = @Status OUTPUT
SET @i=@i+1
END
答案 1 :(得分:0)
这可以使用Shell Script实现,如下所示。
$categories = Invoke-SqlCmd -ServerInstance SERVERINSTANCENAME -Database DATABASENAME -Query "use yourDBName;select categories from yourtable;"
foreach($category in $categories){
$categoryName = $category.name
$attachmentFilePath = "D:\$categoryName.csv"
$QueryFmt = "Select * from yourtable where categories=$categoryName"
Invoke-Sqlcmd -ServerInstance SERVERINSTANCENAME -Database DATABASENAME -Query $QueryFmt | Export-CSV $attachmentFilePath
}