Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export values from SQL Server to txt file

I want to export values from SQL Server to txt file. I know about BCP, there I need to give either query or table name to export data from a table. I don't want to export data but I want to export values that are assigned to variable. How can I do that, any help?

like image 970
niren Avatar asked Sep 05 '13 11:09

niren


1 Answers

Use a query to collect the variables you want to export. Something like this:

DECLARE @var1 INTEGER
DECLARE @var2 INTEGER

SELECT @var1 = 10
SELECT @var2 = 22

SELECT 'variable 1' AS VarName, @var1 AS VarValue
UNION
SELECT 'variable 2' AS VarName, @var2 AS VarValue

Use this query statement in the following command. Use queryout and replace [querystatement] with the statement above, or use a variable for the query string.

EXEC master..XP_CMDSHELL 'bcp "[querystatement]" queryout "c:\spt_values.dat"'

If the variable needs to be declared outside the statement:

DECLARE @cmd varchar(1000)
DECLARE @sql varchar(8000) 
DECLARE @var1 int
SELECT @var1 = 10
SET @cmd='"select '+CAST(@var1 AS VARCHAR(10))+'"' 
SELECT @sql = 'bcp '+@cmd+' queryout I:\File\mytest.txt -c -t -T -S YAMUNA\SQLEXPRESS';
exec xp_cmdshell @sql;
like image 58
Wietze314 Avatar answered Sep 28 '22 06:09

Wietze314