Это возможно, но у вас должно быть достаточно прав для запуска xp_cmdshell и специальных распределенных запросов.
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