Create new file every time the xp_cmdshell command is executed

2

I am working with SQL and what I want is that every time I execute the xp_cmdshell command, a new file is generated, since as I currently have it, write the same one, I leave the code of my query :

DECLARE @Comando VARCHAR(2048) 
SET @Comando = 'bcp "Select * FROM DataBase.dbo.Table" '
+ 'queryout "C:\SAP\Prueba.txt" '
+ '-S "WIN-7A84OQD1HG6\SQLEXPRESS" '
+ '-U "sa" -P "123" -c' 
EXEC xp_cmdshell @Comando;
    
asked by Pistche Lawliet 08.08.2017 в 17:49
source

1 answer

4

Change this line:

+ 'queryout "C:\SAP\Prueba.txt" '

For this:

+ 'queryout "C:\SAP\Prueba ' + Convert(VARCHAR(50),NEWID()) + '.txt" '

This way you will always have a different file name since NewId() is a function of TSql that returns a unique identifier ( uniqueidentifier ), this in turn you must convert it to VARCHAR to be able to concatenate it with the name of the file.

If you want to test the operation try this multiple times in your SQL Server Management Studio:

PRINT '"C:\SAP\Prueba ' + Convert(VARCHAR(50),NEWID()) + '.txt"'

link

    
answered by 08.08.2017 / 17:58
source