Pergunta

I already know, in a T-SQL stored procedure, how to create a file via a bcp command called using xp_cmdshell. Basic example:

DECLARE @cmd varchar(4000)
SET @cmd='bcp "SELECT * FROM myTable FOR XML RAW" queryout D:\myFile.xml -c -T'
EXEC xp_cmdshell @cmd

Now my problem is: in my case, the query is very long, with lots of nested queries. Yes it fits in a varchar, but writing it as a string in quotes makes it unmaintanable. And the result of the query is thousands of lines long so it doesn't fit in a varchar.

Is there a way where I could write my query in plain T-SQL and then send the result to my bcp command without having to put neither the query, nor its result, in a varchar?

I know that SSIS packages could be a solution, but I would like to avoid it as much as possible.

Foi útil?

Solução 2

The solution is quite simple: as suggested by Pepto, bcp can execute a stored procedure instead of a SELECT.

So :

DECLARE @cmd varchar(200)
SET @cmd='bcp "execute MyDb.dbo.MySP" queryout D:\myFile.xml -c -T'
EXEC xp_cmdshell @cmd

Where MySP is a stored procedure containing my huge SELECT statement.

Outras dicas

Have you considered (sorry can't tell from question) to write your output into a Temp Table using those same queries within a Stored Procedure, and then using bcp to copy the output of that Temp Table before dropping it?

I've done this many times and works like a charm. But may not be applicable here.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top