0

Using the code below (which I found here), a variable with 20 million rows is being created. Where do I find the stored variable. I was able to locate the tables I've created but this particular variable isn't visible.

My end goal is to export this variable and its values in a CSV format. How do I make that happen.

Declare @p_NumberOfRows Bigint

--We need 20 million rows

Select @p_NumberOfRows=20000000;

With Base As
(
Select 1 as n
Union All
Select n+1 From Base Where n < Ceiling(SQRT(@p_NumberOfRows))
),
Expand As
(
Select 1 as C
From Base as B1, Base as B2
),
Nums As
(
Select Row_Number() OVER(ORDER BY C) As n
From Expand
)
Select n from Nums Where n<=@p_NumberOfRows

--Remove Maximum Recursion level constraint

OPTION (MaxRecursion 0);
oivemaria
  • 453
  • 4
  • 20
  • 1
    Variables are not stored because they are not persistent. That means if you want to do something more permanent then you need to do it in your code. – Sean Lange Feb 25 '16 at 20:34
  • 1
    You're not creating a variable, you're generating a result set. `@p_NumberOfRows` is a variable, but it has exactly one value. Here's how to export to CSV for a one-time event: http://stackoverflow.com/questions/3169220/export-query-result-to-csv-file-in-sql-server-2008. To do it in code for repeatability: http://dba.stackexchange.com/questions/23566/writing-select-result-to-a-csv-file – Tom H Feb 25 '16 at 20:37
  • Thanks that definitely helped – oivemaria Feb 25 '16 at 22:42

1 Answers1

1

well depending on how you are handling the result set in your application that is going to create the csv, there seem to be several ways to go.

First add the variable count to every row returned in the select

Select n, @p_NumberOfRows as NumberOfRows from Nums Where n<=@p_NumberOfRows

Or you could return two results sets, one with the data and one with the number of rows variable

Select n from Nums Where n<=@p_NumberOfRows
select @p_NumberOfRows as NumberOfRows 

Or you could store the number of rows variable in a table with a run_Instance_Id and a date and then pull from that. This is only if you need to see the number of rows at some future date that was sent on a particular run.

HLGEM
  • 94,695
  • 15
  • 113
  • 186