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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With