与查询中的引号和双引号混淆

时间:2012-06-13 22:19:39

标签: sql sql-server sql-server-2008 tsql ssms

我的查询效果非常好:

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'

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

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

1 个答案:

答案 0 :(得分: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的引用,因为我认为the catalog views are more reliable and more consistent