【发布时间】:2021-02-26 14:37:24
【问题描述】:
我使用 SQL Server 2012 我收到此错误:
在')'附近预期条件的上下文中指定的非布尔类型的表达式
我认为这是因为它无法处理 'N/A' OR Null 或 Text。
如何修改动态 SQL 以接受 N/A AND NULL ?
请问这个问题怎么解决?
我的样本数据
CREATE TABLE #Allfeatures
(
ZPLID INT,
ZFeatureKey nvarchar(20),
IsNumericValue int
)
INSERT INTO #Allfeatures (ZPLID, ZFeatureKey, IsNumericValue)
VALUES (75533, '1505730036', 0)
CREATE TABLE #Condition
(
Code nvarchar(20),
ZFeatureKey nvarchar(20),
ZfeatureType nvarchar(20),
EStrat nvarchar(20),
EEnd NVARCHAR(10)
)
INSERT INTO #Condition (Code, ZFeatureKey, ZfeatureType, EStrat, EEnd)
VALUES ('8535400000', '1505730036', NULL, '>1000', ' '),
('8535400000', '1505730036', NULL, '>280AV', ' '),
('8535400000', '1505730036', NULL, 'N/A', ' '),
('8535400000', '1505730036', NULL, NULL, ' ')
CREATE TABLE #PartAttributes
(
PartID INT,
ZFeaturekEY NVARCHAR(20),
AcceptedValuesOption_Value INT,
Name nvarchar(20)
)
INSERT INTO #PartAttributes (PartID, ZFeaturekEY, AcceptedValuesOption_Value, Name)
VALUES (4977941, 1505730036, 280, '280VDC'),
(4977936, 1505730036, 280, '280VDC'),
(4977935, 1505730036, 280, '280VDC')
DECLARE @Sql nvarchar(max)
DECLARE @ConStr nvarchar(max)
SET @ConStr = STUFF((SELECT CONCAT(' Or (PM.ZfeatureKey= ', CC.ZfeatureKey , IIF(CC.ZfeatureType='Qualifications',' And AcceptedValuesOption_Value ' , ' And translate(Name, ''VDCA'', space(4)) ' ) , CAST(
cast(LEFT(SUBSTRING(EStrat, PATINDEX('%[<>0-9.-]%', EStrat), 2500),
PATINDEX('%[^<>0-9.-]%', SUBSTRING(EStrat, PATINDEX('%[<>0-9.-]%', EStrat), 2500) + 'X') -1) as nvarchar(2500))
--EStrat
AS NVARCHAR(2500)), ')')
FROM #Condition CC INNER JOIN #Allfeatures AL ON AL.ZfeatureKey = CC.ZfeatureKey AND AL.IsNumericValue =0
where EStrat <> 'N/A'
FOR XML PATH(''), TYPE).value('(./text())[1]','varchar(max)'),1,3,'')
----------------
SET @Sql= CONCAT(' SELECT PartID, Code, Count(1) as ConCount
FROM #PartAttributes PM
INNER JOIN #Condition Co ON Co.ZfeatureKey = PM.ZfeatureKey ',
'Where 1=1 and (', @ConStr, ' ) Group By PartID,Code ' ,
' Having Count(1)> = ',(SELECT COUNT(1) FROM #Condition))
EXEC (@SQL)
【问题讨论】:
-
好好学习这一课。看不到动态sql就无法调试!所以 - 打印或选择您生成的查询并将该值添加到您的问题中。
-
提示:如果将生成的 SQL 语句复制到 SSMS 中的查询窗口,则可以使用 parse 函数来验证语法。如需更多信息,请参阅SQL Server Management Studio and T-SQL Options to Prevent Code from Running in Production。
标签: sql-server tsql stored-procedures sql-server-2012 sql-function