3

下面的 SQL 得到我需要的东西:

 SELECT TOP (50) [nodeId] 
 FROM [dbo].[cmsContentXml] 
 WHERE [xml] like '%creatorID="29"%'    
   AND [xml] like '%nodeType="1086"%' 
 ORDER BY [nodeId] DESC

我需要将数字作为参数传递,所以我有以下内容:

exec sp_executesql N'SELECT TOP (@max) [nodeId] FROM [dbo].[cmsContentXml] WHERE [xml] like ''%creatorID="@creatorID"%''    AND [xml] like ''%nodeType="@nodeType"%'' ORDER BY [nodeId] DESC',N'@max int,@creatorID int,@nodeType int',@max=50,@creatorID=29,@nodeType=1086

但是,它没有返回任何记录,有什么想法吗?

4

2 回答 2

1

尝试修改您的 SQL 语句,以便通过在将参数作为语句的一部分发送时添加参数来构建语句,例如

'SELECT TOP ' + @max + ' [nodeId] '.....
于 2010-05-26T10:23:45.310 回答
0

问题在于您尝试使用 LIKE 子句中的参数的方式。

即@creatorID 和@nodeType 的值实际上并未在LIKE 条件中使用-您实际上是在搜索xml,其中(例如)它的字面意思类似于'%creatorID="@creatorID"'

您需要确保您的查询不会出现:

SELECT TOP (@max) [nodeId] 
FROM [dbo].[cmsContentXml] 
WHERE [xml] like '%creatorID="@creatorID"%'
    AND [xml] like '%nodeType="@nodeType"%' 
ORDER BY [nodeId] DESC

但反而:

SELECT TOP (@max) [nodeId] 
FROM [dbo].[cmsContentXml] 
WHERE [xml] like '%creatorID="' + CAST(@creatorID AS VARCHAR(50)) + '"%'
    AND [xml] like '%nodeType="' + CAST(@nodeType AS VARCHAR(50)) + '"%' 
ORDER BY [nodeId] DESC

所以像:

DECLARE @SQL NVARCHAR(1000)
SET @SQL = '
    SELECT TOP (@max) [nodeId] 
    FROM [dbo].[cmsContentXml] 
    WHERE [xml] like ''%creatorID="'' + CAST(@creatorID AS VARCHAR(50)) + ''"%''    
       AND [xml] like ''%nodeType="'' + CAST(@nodeType AS VARCHAR(50)) + ''"%'' 
    ORDER BY [nodeId] DESC'

exec sp_executesql @SQL,
    N'@max int,@creatorID int,@nodeType int',
    @max=50,@creatorID=29,@nodeType=1086
于 2010-05-26T10:39:05.587 回答