2009-07-29 113 views
1

继续本主题中的某个答案; Using XQuery in Linq To SQL?使用XQuery参数编写SQL函数

我试图创建一个sql表函数,它将采取参数为了执行对XML数据的查询。该函数可以被linq查询使用。

问题是我有;

  1. 如果我采取从前面提到的线程的代码我得到值的“xml数据类型方法的参数1‘’必须是字符串文字”错误。

  2. 如果我写使用sp_executesql的然后我得到一个我自己的函数“只有函数和扩展存储过程可以从函数中执行。”

这是我的功能;

CREATE FUNCTION fnGetOpManualXMLDataFromInt 
( 
    -- Add the parameters for the function here 
    @valueXPath varchar(255), 
    @criteriaXPath varchar(255), 
    @intCriteriaVal int 
) 
RETURNS @returntable TABLE 
(
omId int, 
xmlNodes xml 
) 
AS 
BEGIN 

DECLARE @strExecute nvarchar(4000), @SingleQuote varchar(1) 
SET @SingleQuote = char(39) 

SET @strExecute = 'insert into @returntable select omID, 
    omText.query(' + @SingleQuote + @valueXPath + @SingleQuote + ') as Value 
    from dbo.htOperationsManuals 
    where omText.value(' + @SingleQuote + @criteriaXPath + @SingleQuote + ', ' + @SingleQuote + 'int' + @SingleQuote + ') = ' + ltrim(str(@intCriteriaVal)) 

exec sp_executesql @strExecute 
return 
end 

这是我的测试;

DECLARE 
@valueXPath varchar(255), 
@criteriaXPath varchar(255), 
@intCriteriaVal int 

SET @valueXPath = '/operationsManual/sections/section/contentItem' 
SET @criteriaXPath = '(/operationsManual/sections/section/contentItem/imageContentItem/imageId)[1]' 
SET @intCriteriaVal = 131 

select * from fnGetOpManualXMLDataFromInt(@valueXPath, @criteriaXPath, @intCriteriaVal) 

任何人都可以想出一种方法来实现这一目标吗?

编辑:顺便说一句,我不直接在linq这样做的原因是,我得到一个错误;

Dim imageUsage = From opmanual In dc.OperationsManuals _ 
        Where opmanual.OutOfService = False _ 
        And opmanual.omText.<sections>.<section>.<contentItem>.<imageContentItem>.<imageId>.Value = imageId _ 
        Select opmanual 

错误;

Message = "Method 'System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement] Elements(System.Xml.Linq.XName)' has no supported translation to SQL." 

回答

1

不能执行动态的XPath,你应该写与XPath函数的参数是文字字符串和这些字符串与sql:variable(@var)嵌入您的参数通常查询。请参阅this thread了解更多信息。

+0

好吧,我可以看到sql:变量可能是要走的路....我无法找到许多类似的例子,其中sql变量保存整个路径......只有在传统意义上使用它的地方保存一个变量用于比较硬编码的xml元素/属性路径。有任何想法吗? – GordonB 2009-07-29 16:15:43