[英]SQL Server 2008 Stored Proc not returning output from dynamic query
[英]sql server stored proc dynamic select
我有以下格式的存儲過程
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
以下存儲的proc由於其中使用了逗號而出現了問題。有人可以讓我知道您是正確的做法嗎?
問題不在於逗號。 您通常有兩個問題:一,您沒有正確地轉義引號。 第二,您沒有正確連接變量。 這是兩個示例:
對於連接變量:在第一行中,您不能執行以下操作:
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'')'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.