编写SQL动态查询时出错

时间:2017-01-31 06:13:31

标签: sql sql-server-2008

我的代码就像这样

DECLARE @QueryText as NVARCHAR(MAX);

SET @QueryText= 'select '"' + m.MACHINE_STREET + '"' AS MACHINE_LOCATION,
A.Country_Code AS Country,
(SELECT mibcp.REMARKS FROM tblMachineContact mibcp
where mibcp.mc_machine_pkey=m.pkey and mibcp.CONTACT_CATEGORY_PKEY=''IR'') AS REMARKS
                 from tblMachine m inner join tblAddress A
on m.Address_Pkey=A.Pkey
                 where m.Site= ''TSN'''

EXEC sp_Machine_Location,NULL,NULL,NULL,@QueryText

运行此动态查询时,我在子查询中收到错误。

(SELECT mibcp.REMARKS    
   FROM tblMachineContact mibcp
 WHERE mibcp.mc_machine_pkey=m.pkey    
   AND mibcp.CONTACT_CATEGORY_PKEY=''IR'') AS REMARKS.

如何避免这种情况?

1 个答案:

答案 0 :(得分:0)

这可能导致你的以下引用的子查询部分将返回超过1条记录,你实际上意味着每行获取1条记录。

(SELECT mibcp.REMARKS FROM tblMachineContact mibcp
where mibcp.mc_machine_pkey=m.pkey and mibcp.CONTACT_CATEGORY_PKEY=''IR'') AS REMARKS

您可以像

那样进行查询
select m.MACHINE_STREET AS MACHINE_LOCATION,
A.Country_Code AS Country,
mibcp.REMARKS 
FROM tblMachineContact mibcp
join tblMachine m on mibcp.mc_machine_pkey = m.pkey 
inner join tblAddress A on m.Address_Pkey = A.Pkey
where m.Site = 'TSN'
and mibcp.CONTACT_CATEGORY_PKEY = 'IR'