sql server存储过程动态选择

时间:2014-05-22 22:14:02

标签: sql-server

我有以下格式的存储过程

create PROCEDURE [dbo].[test proc] 
@identifier varchar(20),
@issuerName varchar(max),
@max_records  int=1000
AS
BEGIN
declare @select nvarchar(30)

SELECT @identifier as '@identifier'
    , (
        SELECT 
        MoodysOrgID as '@MoodysOrgID'
        ,ReportDate as '@ReportDate'
        ,m.UpdateTime as '@UpdateTime'
        ,m.FileCreationDate as '@FileCreationDate'
        from mfm_financial_ratios m
        inner join mfm_financial_ratios_coa c on c.AcctNo = m.AcctNo
        where ReportDate in (select distinct top (@max_records) reportdate from mfm_financial_ratios where MoodysOrgID = m.MoodysOrgID) 
        and m.MoodysOrgID=(select top 1 IssuerID_Moodys as id from loans where LIN=@identifier or LoanXID=@identifier
                           and ParentName_Moodys=@issuerName and IssuerID_Moodys is not null)
        order by ReportDate desc
        FOR XML PATH('FinRatios'), TYPE
    )
    FOR XML PATH('FinRatiosHistory')

END

但我想通过查询执行动态sql

我的存储过程看起来像

create PROCEDURE [dbo].[test proc] 
    @identifier varchar(20),
    @issuerName varchar(max),
    @max_records  int=1000
    AS
    BEGIN
    declare @select nvarchar(30)

set    @select = N'SELECT @identifier as '@identifier'
        , (
            SELECT 
            MoodysOrgID as '@MoodysOrgID'
            ,ReportDate as '@ReportDate'
            ,m.UpdateTime as '@UpdateTime'
            ,m.FileCreationDate as '@FileCreationDate'
            from mfm_financial_ratios m
            inner join mfm_financial_ratios_coa c on c.AcctNo = m.AcctNo
            where ReportDate in (select distinct top (@max_records) reportdate from mfm_financial_ratios where MoodysOrgID = m.MoodysOrgID) 
            and m.MoodysOrgID=(select top 1 IssuerID_Moodys as id from loans where LIN=@identifier or LoanXID=@identifier
                               and ParentName_Moodys=@issuerName and IssuerID_Moodys is not null)
            order by ReportDate desc
            FOR XML PATH('FinRatios'), TYPE
        )
        FOR XML PATH('FinRatiosHistory')'
exec @select

    END

以下存储过程由于其中使用了逗号而产生问题。可以让某人告诉我你的正确做法

1 个答案:

答案 0 :(得分:0)

问题不在于逗号。你大多有两个问题:一,你没有正确地逃避报价。第二,你没有正确地连接你的变量。以下是两者的示例:

对于连接变量:在第一个选择行中,您不能这样做:

SELECT @identifier as '@identifier'

因为sql不知道如何处理@identifier。您应该以这种方式连接变量:

SELECT @identifier as ' + @identifier + '.. everything else goes here

此外,当你必须连接max_records时,由于它是一个int变量,你应该首先将它转换为varchar,如下所示:

select distinct top (' + cast(@max_records as varchar(10) + ')  ....

每当你在字符串中间使用一个变量(例如@max_records)时,你必须连接它,以便SQL知道它是一个变量而不仅仅是一个字符串。你没有使用max_records,@ issuerName等

对于转义引号:当您不希望您的选择字符串意外结束时,您需要转义单引号。例如:

FOR XML PATH('FinRatiosHistory')'

你应该用双引号来逃避它们(google转义单引号sql如果你没有得到它)​​

FOR XML PATH(''FinRatiosHistory'')'