如何摆脱以下动态 SQL 中的多个转换函数?
IF @MediaTypeID > 0 or @MediaGroupID > 0
BEGIN
SET @SQL = @SQL + 'INNER JOIN (SELECT lmc.ID FROM Lookup_MediaChannels (nolock) lmc
INNER JOIN Lookup_SonarMediaTypes (nolock) lsmt ON lmc.SonarMediaTypeID = lsmt.ID
WHERE (ISNULL('+ CONVERT(VARCHAR(10),@MediaTypeID) +',0) = 0 OR lsmt.ID = '+ CONVERT(VARCHAR(10),@MediaTypeID) +')
AND (ISNULL('+ CONVERT(VARCHAR(10),@MediaGroupID)+',0) = 0 OR lsmt.SonarMediaGroupID = '+ CONVERT(VARCHAR(10),@MediaGroupID) +'))t ON t.ID = lmc.ID '
我尝试先转换它们并使用变量而不是下面的转换调用
IF @MediaTypeID > 0 or @MediaGroupID > 0
BEGIN
SET @TypeID = CONVERT(VARCHAR(10),@MediaTypeID)
SET @GroupID = CONVERT(VARCHAR(10),@MediaGroupID)
SET @SQL = @SQL + 'INNER JOIN (SELECT lmc.ID FROM Lookup_MediaChannels (nolock) lmc
INNER JOIN Lookup_SonarMediaTypes (nolock) lsmt ON lmc.SonarMediaTypeID = lsmt.ID
WHERE (ISNULL('+ @TypeID +',0) = 0 OR lsmt.ID = '+ @TypeID +')
AND (ISNULL('+ @GroupID+',0) = 0 OR lsmt.SonarMediaGroupID = '+ @GroupID +'))'
END
但它给了我这个错误
消息 245,级别 16,状态 1,第 13
行将 varchar 值 ',0) = 0 或 lsmt.ID = ' 转换为数据类型 int 时转换失败。