我将参数传递给链接服务器,如下所示:
DECLARE
@QRY01 VARCHAR(8000)
,@WIP_PRM VARCHAR(12)
--START SEARCHING WIP_AUTO_KEY IN COST_AUDIT_LOG FROM LAST RECORD INCLUDED IN tbl_WIPLOG1
SET @WIP_PRM = CONVERT(VARCHAR(12),(SELECT MAX(WIP_AUTO_KEY) FROM tbl_WIPLOG1))
SET @QRY01 = '
SELECT *
FROM
OPENQUERY(LINKED_SERVER,
''SELECT DISTINCT
QCTL.WIP_AUDIT_LOG.WIP_AUTO_KEY
,QCTL.WIP_AUDIT_LOG.WOO_AUTO_KEY
FROM QCTL.WIP_AUDIT_LOG
WHERE
QCTL.WIP_AUDIT_LOG.WIP_AUTO_KEY > '+CHAR(39) + CHAR(39)+CAST(@WIP_PRM AS nvarchar(500))+CHAR(39) + CHAR(39)+N''')
EXEC(@QRY01)
由于整个语句都括在方括号中,因此OPENQUERY语句中参数的格式似乎不正确或需要在其前面使用关键字来将其指定为文本。如果我按如下所示键入参数的值,则查询有效,但不采用上述格式。
SET @QRY01 = '
SELECT *
FROM
OPENQUERY(LINKED_SERVER,
''SELECT DISTINCT
QCTL.WIP_AUDIT_LOG.WIP_AUTO_KEY
,QCTL.WIP_AUDIT_LOG.WOO_AUTO_KEY
FROM QCTL.WIP_AUDIT_LOG
WHERE
QCTL.WIP_AUDIT_LOG.WIP_AUTO_KEY > ''''1432697'''' '
EXEC(@QRY01)
如何使查询接受正确格式的参数?
答案 0 :(得分:0)
@leon,您需要取出CHAR(39)来简化查询。
这是下面的修改版本:
DECLARE
@QRY01 VARCHAR(8000)
,@WIP_PRM VARCHAR(12)
--START SEARCHING WIP_AUTO_KEY IN COST_AUDIT_LOG FROM LAST RECORD INCLUDED IN tbl_WIPLOG1
SET @WIP_PRM = CONVERT(VARCHAR(12),(SELECT MAX(WIP_AUTO_KEY) FROM tbl_WIPLOG1))
SET @QRY01 = '
SELECT *
FROM
OPENQUERY(LINKED_SERVER,
''SELECT DISTINCT
QCTL.WIP_AUDIT_LOG.WIP_AUTO_KEY
,QCTL.WIP_AUDIT_LOG.WOO_AUTO_KEY
FROM QCTL.WIP_AUDIT_LOG
WHERE
QCTL.WIP_AUDIT_LOG.WIP_AUTO_KEY > '+CAST(@WIP_PRM AS nvarchar(500))+ N''')'
EXEC(@QRY01)
这应该为您提供以下输出:
SELECT *
FROM
OPENQUERY(LINKED_SERVER,
'SELECT DISTINCT
QCTL.WIP_AUDIT_LOG.WIP_AUTO_KEY
,QCTL.WIP_AUDIT_LOG.WOO_AUTO_KEY
FROM QCTL.WIP_AUDIT_LOG
WHERE
QCTL.WIP_AUDIT_LOG.WIP_AUTO_KEY > 1432697')