如何将多值字符串作为单个参数传递给sql server中的BCP查询

时间:2013-12-07 06:59:20

标签: sql-server tsql bcp

这里面临将多值参数传递给bcp查询的问题。

在我的场景中,参数是

@CustomFieldsHeaders ='CS Check','CS Date','CS Drop','CS Radio','RSP Text','RSP Date','RSP Check','RSP radio','RSP Drp','DOB'  

我需要将上述内容作为单个参数传递。

以下是我的查询供参考,请帮忙

  DECLARE @CustomFieldsHeaders AS VARCHAR(MAX)
        SELECT @CustomFieldsHeaders = COALESCE(@CustomFieldsHeaders+',' ,'') + ''''+CAST(FieldName as varchar(max))+''''  FROM ManageFields
        PRINT @CustomFieldsHeaders


        DECLARE @CustFieldNames VARCHAR(MAX)
        SELECT @CustFieldNames =''+ COALESCE(@CustFieldNames+',' ,'') + CAST(ContactFieldName as varchar(max))+''
        from ManageFields
        print  @CustFieldNames

   DECLARE @SQL AS VARCHAR(8000) 
   DECLARE @StoredProcedure AS VARCHAR(8000) 
     SET @StoredProcedure=N'"EXEC  QA31_28thNov2013.dbo.GetAllRecsBasedOnListIds_BCPTest_1 117, NULL, '+@CustFieldNames+', '''+@CustomFieldsHeaders+''' " '         
        SET @SQL = N'bcp '+@StoredProcedure + ' queryout '+'D:\BCP_WEBREPORT\QA_v1_23rdSep2013\BounceReport\12-07-13\TESTREPORT13.CSV'  +' -c -t, -S PSPL-06 -Usa -Psa!2013'  
        PRINT @SQL 
        EXEC MASTER..XP_CMDSHELL @SQL 

1 个答案:

答案 0 :(得分:0)

你需要逃避字符串中的's'吗?你可以逃脱'有''。有一个函数会为你做这个名为QUOTENAME() 还有similar question with some solutions here