Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
编写SQL动态查询时出错_Sql_Sql Server 2008 - Fatal编程技术网

编写SQL动态查询时出错

编写SQL动态查询时出错,sql,sql-server-2008,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.CONTAC

我的代码是这样的

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.

如何避免这种情况?

这可能是因为下面引用的子查询部分将返回多条记录,而您实际上打算每行获取一条记录

(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'

您会遇到什么样的错误?还有DBMS标签,您正在使用哪个DBMS?请确保您的内部查询(选择mibcp。备注…为每行获取单个值。我正在使用MS SQL Server 2008,我需要在子查询中获取contact_category_pkey=IR,以便如果存在任何值,它将返回结果,否则它将返回null。如果我在where条件中添加此部分,它将仅获取contact_category作为IR,这不是我的要求。)我会拿很多类别,但我只想评论IR。有什么建议吗?