如何在 @Var VERSION 2 之前和之后使用文字在 Case 语句中显示 @Var 结果

How to display the @Var result inside a Case statement with literals before and after the @Var VERSION 2

这是我的查询:

 DECLARE @RecordCount as INT
 DECLARE @today as VARCHAR(10)

 SET @today = convert(varchar(10),getdate(),120)
  Set @RecordCount = (Select COUNT(*)
 FROM tableABC

 select case when @RecordCount = 0
  THEN 'There was no data found for tableABC: ' + @Today 
  ELSE 'tableABC imported ' + @RecordCount +' rows for date range ' + @Today
  END

错误信息

Msg 245, Level 16, State 1, Line 8 Conversion failed when converting the varchar value 'tableABC imported' to data type int.

为什么会出现此错误???

SQL 服务器尝试将字符串转换为整数,因为 Data Type Precedence:

When an operator combines two expressions of different data types, the rules for data type precedence specify that the data type with the lower precedence is converted to the data type with the higher precedence. If the conversion is not a supported implicit conversion, an error is returned.

INT 在优先级列表中为 16,字符串常量 (VARCHAR) 较低。所以 SQL 服务器尝试将每个字符串转换为 INT.

RecordCount 转换为字符串:

DEMO

select 
   case when @RecordCount = 0
     THEN 'There was no data found for tableABC: ' + @Today 
     ELSE 'tableABC imported ' + CAST(@RecordCount AS NVARCHAR(100)) +' rows for date range ' + @Today
   end

您还应该考虑使用 CONCAT 代替 + 进行字符串连接。那你就不需要施法了:

select 
   case when @RecordCount = 0
     THEN CONCAT('There was no data found for tableABC: ',@Today)
     ELSE CONCAT('tableABC imported ', @RecordCount,' rows for date range ', @Today)
   end

另一个解决方案是使用FORMATMESSAGE:

DECLARE @RecordCount as INT = 1;
DECLARE @today as VARCHAR(10) = convert(varchar(10),getdate(),120);

SELECT
  CASE 
   WHEN @RecordCount = 0 THEN FORMATMESSAGE('There was no data found for tableABC: %i', @RecordCount)
   ELSE FORMATMESSAGE('tableABC imported %i rows for date range %s', @RecordCount, @today)
  END
select case when @RecordCount = 0
  THEN 'There was no data found for tableABC: ' + @Today 
  ELSE 'tableABC imported ' + cast(@RecordCount as varchar(10)) +' rows for date range ' + @Today
  END

问题是,当您将内容合并到一个字符串中时,该字符串的所有元素都必须是基于文本的数据类型,而不是数字数据类型。由于您之前将 @RecordCount 用作整数,因此最好的办法是在 else 语句中将其转换为 varchar。 varchar 和 int 之间存在隐式转换,但 SQL 服务器出于超出我理解的原因,选择始终尝试将文本转换为 int,而不是相反。因此 tex 不能转换,因此您会收到错误消息。