选择未知的列数为csv

时间:2015-02-10 04:56:10

标签: sql-server-2008

假设我在表格和主键列中有未知的N列,因此我想要CSV格式的特定主键的所有列。

N可以是任意数量的列

ID Name    Class   RollNo  Language  State   Country

1  Aditya  12th    5       English   C.A.    USA

2  XYZ     X       3        AA       AA      AAA 

输出应该像

1,Aditya,12th,5,English,CA,USA

2,XYZ,X,3,AA,AA,AAA
SQL SERVER中的

1 个答案:

答案 0 :(得分:0)

试试这个

       DECLARE @sql        VARCHAR(8000),
        @dbname     VARCHAR(50)='',
        @schemaname VARCHAR(50)='dbo',
        @tablename  VARCHAR(50)=''

SELECT @sql = 'bcp ' + @dbname + '.' + @schemaname + '.'
              + @tablename
              + ' out
c:\bcp\tablename.csv -u username -p password -S'
              + @@SERVERNAME
EXEC master..xp_cmdshell
  @sql

--[Note:The path should be your server path]
--TO configure xp_cmdshell
EXEC sp_configure
  'show advanced options',
  1;

GO

-- To update the currently configured value for advanced options.
RECONFIGURE;

GO

-- To enable the feature.
EXEC sp_configure
  'xp_cmdshell',
  1;

GO

-- To update the currently configured value for this feature.
RECONFIGURE;

GO