1

我有一个很好用的查询:

CREATE Procedure BCP_Text_File
(  
    @table varchar(100),  
    @FileName varchar(100)  
)  
AS
    If exists(Select * from information_Schema.tables where table_name=@table)
    Begin
        Declare @str varchar(1000)  
        set @str='Exec Master..xp_Cmdshell ''bcp "Select * from '+db_name()+'..'+@table+'" queryout "'+@FileName+'" -c'''  
        Exec(@str)  
    end
    else
        Select 'The table '+@table+' does not exist in the database'

但我需要在其中添加:

select column_name 
from information_schema.columns
where table_name = @table
order by ordinal_position

到目前为止,我有:

   alter Procedure BCP_Text_File
   (  
      @table varchar(100),  
      @FileName varchar(100)  
    )  
    AS 
       If exists(Select * from information_Schema.tables where table_name=@table)
       Begin
           Declare @str varchar(1000)  
           set @str='Exec Master..xp_Cmdshell ''bcp "

           select column_name 
           from information_schema.columns
           where table_name = '+db_name()+'..'+@table+'
           order by ordinal_position

           Select * from '+db_name()+'..'+@table+'" queryout "'+@FileName+'" -c'''  
           Exec(@str)  
       end
       else
           Select 'The table '+@table+' does not exist in the database'

但我认为我放错了单引号和/或双引号。我正在添加此选择语句,以便我的结果将字段名称作为第一行。

非常感谢任何帮助或指导。

4

1 回答 1

3

也许这就是你想要的?这假设(a)您的列名中没有逗号,并且(b)每列的输出在隐式转换为字符串时是可以的。

ALTER PROCEDURE dbo.BCP_Text_File
    @table    NVARCHAR(255),  
    @filename VARCHAR(100)  
AS
BEGIN
  SET NOCOUNT ON;

  IF OBJECT_ID(@table) IS NOT NULL
  BEGIN
    DECLARE 
        @sql NVARCHAR(MAX), 
        @cols NVARCHAR(MAX) = N'';

    SELECT @cols += ',' + name
      FROM sys.columns
      WHERE [object_id] = OBJECT_ID(@table)
      ORDER BY column_id;

    SELECT @cols = STUFF(@cols, 1, 1, '');

    SET @sql = N'EXEC master..xp_cmdshell ''bcp "SELECT ''''' 
        + REPLACE(@cols, ',', ''''',''''') + ''''' UNION ALL SELECT ' 
        + 'RTRIM(' + REPLACE(@cols, ',', '),RTRIM(') + ') FROM ' 
        + DB_NAME() + '..' + @table + '" queryout "' + @filename + '" -c''';  
    
    EXEC sp_executesql @sql;
  END
  ELSE
  BEGIN
    SELECT 'The table '+@table+' does not exist in the database';
  END
END
GO

但我必须同意你从其他人那里得到的关于这个和其他问题的建议——这种方法非常脆弱。你正试图用压路机打开开心果。

PS 我删除了对的引用INFORMATION_SCHEMA,因为我认为目录视图更可靠且更一致

于 2012-06-13T22:51:34.727 回答