我正在使用在gridview上使用的查询来选择要显示的数据:
SELECT [Theme].[PK_Theme], [Theme].[Name], [ThemeType].[Type]
FROM [Theme]
LEFT OUTER JOIN [ThemeType]
ON [Theme].[ThemeTypeId] = [ThemeType].[PK_ThemeType]
JOIN [ProductTheme] ON [ProductTheme].[ThemeId]=[Theme].[PK_Theme]
WHERE ProductTheme.ProductID LIKE @productParam
AND ProductTheme.ThemeId = Theme.PK_Theme
AND COALESCE([THEME].[THEMETYPEID], 'null') LIKE @assignedParam
GROUP BY [Theme].[Name], [ThemeType].[Type], [Theme].[PK_Theme]
ORDER BY CASE WHEN [ThemeType].[Type] IS NULL THEN 0 ELSE 1 END, [Theme].[Name]
列[THEME]。[THEMETYPEID]以前是varchar(50)但已更改为int。
我现在收到此错误:
Conversion failed when converting the varchar value 'NULL' to data type int.
有一点奇怪的是,我直接查询服务器上面的语句是否有效,(我更改了值的参数)但是它在服务器控件中不起作用。
更新后的列允许空值。如何在这种情况下检查一个int的Null并让查询像以前一样工作?
编辑如果两个参数都分配了'%',我希望结果如下:
答案 0 :(得分:3)
这一行:
AND COALESCE([THEME].[THEMETYPEID], 'null') LIKE @assignedParam
应该是(没有单引号):
AND COALESCE([THEME].[THEMETYPEID], NULL) LIKE @assignedParam
因为'null'
是普通字符串,而您可能打算表示NULL
值
或许您应该将其更改为:
AND COALESCE([THEME].[THEMETYPEID], 0) LIKE @assignedParam
由于ThemeTyeID是一个int
<强>更新强>
试试这个:
SELECT [Theme].[PK_Theme] ,
[Theme].[Name] ,
[ThemeType].[Type]
FROM [Theme]
LEFT OUTER JOIN [ThemeType] ON [Theme].[ThemeTypeId] = [ThemeType].[PK_ThemeType]
JOIN [ProductTheme] ON [ProductTheme].[ThemeId] = [Theme].[PK_Theme]
WHERE ProductTheme.ProductID LIKE @productParam
AND ProductTheme.ThemeId = Theme.PK_Theme
AND 1 = CASE WHEN [THEME].[THEMETYPEID] IS NULL THEN 1
WHEN [THEME].[THEMETYPEID] LIKE @param THEN 1
END
GROUP BY [Theme].[Name] ,
[ThemeType].[Type] ,
[Theme].[PK_Theme]
ORDER BY CASE WHEN [ThemeType].[Type] IS NULL THEN 0
ELSE 1
END ,
[Theme].[Name]
但是我们警告说,如果这样可以按照您的意愿工作,那么它就不如为每个案例编写单独的查询一样有效。也许和他们结合......
答案 1 :(得分:0)
请尝试以下代码:
SELECT [Theme].[PK_Theme], [Theme].[Name], [ThemeType].[Type]
FROM [Theme]
LEFT OUTER JOIN [ThemeType]
ON [Theme].[ThemeTypeId] = [ThemeType].[PK_ThemeType]
JOIN [ProductTheme] ON [ProductTheme].[ThemeId]=[Theme].[PK_Theme]
WHERE ProductTheme.ProductID LIKE @productParam
AND ProductTheme.ThemeId = Theme.PK_Theme AND [Theme].[ThemeTypeId] IS NOT NULL
AND COALESCE([THEME].[THEMETYPEID], 'null') LIKE @assignedParam
GROUP BY [Theme].[Name], [ThemeType].[Type], [Theme].[PK_Theme]
ORDER BY CASE WHEN [ThemeType].[Type] IS NULL THEN 0 ELSE 1 END, [Theme].[Name]