0

I have this query:

WITH InfoNeg AS
(
    SELECT DISTINCT
        n.idcliente,
        CASE 
            WHEN DATEDIFF(MONTH, MAX(n.fechanegociacion), GETDATE()) <= 2 
                THEN 'Negociado 6 meses' 
            ELSE NULL 
        END AS TipoNeg
    FROM 
        SAB2NewExports.dbo.negociaciones AS n
    WHERE 
        Aprobacion = 'Si' 
        AND cerrado = 'Si'
    GROUP BY 
        n.idcliente
), Multi AS
(
    SELECT DISTINCT 
        idcliente, COUNT(distinct idportafolio) AS NumPorts
    FROM 
        orangerefi.wfm.wf_master_HIST
    WHERE 
        YEAR(Fecha_BKP) = 2021 
        AND MONTH(Fecha_BKP) = 08
    GROUP BY 
        idcliente
)
SELECT DISTINCT
    m.IdCliente, c.Nombre1
FROM 
    orangerefi.wfm.wf_master_HIST as m
LEFT JOIN 
    InfoNeg ON m.idcliente = InfoNeg.idcliente
LEFT JOIN 
    Multi ON m.IdCliente = Multi.idcliente
LEFT JOIN 
    SAB2NewExports.dbo.Clientes AS c ON m.IdCliente = c.IdCliente
WHERE 
    CanalTrabajo = 'Callcenter - Outbound' -- Cambiar aca
    AND YEAR (Fecha_BKP) = 2021 
    AND MONTH(Fecha_BKP) = 08 
    AND GrupoTrabajo IN ('Alto')    -- Cambiar aca
    AND Bucket IN (1, 2)            -- Cambiar aca
    AND Multi.NumPorts > 1 
    AND Infoneg.TipoNeg IS NULL

When I run it, I get 30 thousand rows and the columns that I get when performing the query are: ClientID, name. I would like it to be saved in an Excel file when I run it, I don't know if it's possible.

Another question, is it possible to create a variable that stores text? I used CONCAT(), but the text being so long is a bit cumbersome, I don't know if there is any alternative.

If you can help me, I appreciate it.

jarlh
  • 42,561
  • 8
  • 45
  • 63

1 Answers1

1

To declare a variable

DECLARE @string VARCHAR(MAX)
SET @string = concat()

then insert whatever you are concatenating

Here is an answer given by carusyte Export SQL query data to Excel I don't know if this is what you're looking for, but you can export the results to Excel like this:

In the results pane, click the top-left cell to highlight all the records, and then right-click the top-left cell and click "Save Results As". One of the export options is CSV.

You might give this a shot too:

INSERT INTO OPENROWSET 
   ('Microsoft.Jet.OLEDB.4.0', 
   'Excel 8.0;Database=c:\Test.xls;','SELECT productid, price FROM dbo.product')
Lastly, you can look into using SSIS (replaced DTS) for data exports. Here is a link to a tutorial:

http://www.accelebrate.com/sql_training/ssis_2008_tutorial.htm

== Update #1 ==

To save the result as CSV file with column headers, one can follow the steps shown below:

Go to Tools->Options Query Results->SQL Server->Results to Grid Check “Include column headers when copying or saving results” Click OK. Note that the new settings won’t affect any existing Query tabs — you’ll need to open new ones and/or restart SSMS.

SCCJS
  • 96
  • 8