So another way you can achieve your goal, guarantee the rows are ordered, and do it in a simple manner that only requires 1 call to xp_cmdshell
is by adding a dummy sort ID column to the UNION ALL
query, and then wrapping it in a CTE or subquery so you can order on it without having to select it:
DECLARE @archivoOUT varchar(800)
DECLARE @sql nvarchar(1000)
SET @archivoOUT = CONCAT('D:\archivosolicitudrestcate', FORMAT (GETDATE(), 'yyyyMMdd'),'.csv')
SET @sql =
CONCAT
(
N'bcp ',
N'"SELECT Column1, Column2, Column3 ',
N'FROM ',
N'( ',
N' SELECT ''Column1Name'' AS Column1, ''Column2Name'' AS Column2, ''Column3Name'' AS Column3, 1 AS SortId',
N' UNION ALL ',
N' SELECT Column1, Column2, Column3, 2 AS SortId ',
N' FROM dbo.TEMP_res ',
N') AS Results ',
N'ORDER BY SortId" ',
N'out ', @archivoOUT, ' -S ', @@SERVERNAME, ' -d CentroMedico -c -T -w'
)
EXEC master..xp_cmdshell @sql
This is kind of the best of both worlds and then some, from the other answers.
Note I'm using CONCAT()
so I can format the query in a human readable way, that's just my preference, it's not required. You can just stuff the whole code in a single line of code if you prefer, like your original BCP query string.