【问题标题】:Printing integer variable and string on same line in SQL在 SQL 的同一行上打印整数变量和字符串
【发布时间】:2014-05-09 13:24:48
【问题描述】:

好的,所以我在 Technet 上搜索了此问题的答案,但无济于事。

我只想打印一个与两个字符串变量连接的整数变量。

这是我的代码,无法运行:

print 'There are ' + @Number + ' alias combinations did not match a record'

这似乎是一个基本的功能,我无法想象在 T-SQL 中是不可能的。但如果不可能,请直说。我似乎找不到一个直接的答案。

【问题讨论】:

  • print 'There are ' + CAST(@Number AS NVARCHAR(100)) + ' alias combinations did not match a record'

标签: sql sql-server tsql


【解决方案1】:
declare @x INT = 1 /* Declares an integer variable named "x" with the value of 1 */
    
PRINT 'There are ' + CAST(@x AS VARCHAR) + ' alias combinations did not match a record' /* Prints a string concatenated with x casted as a varchar */

【讨论】:

  • 我喜欢 Cast 方法。简短而甜蜜,并将原始变量保留为我需要的 int。
  • 哈,我会立即接受它,但它不会让我再等 6 分钟。
【解决方案2】:

数字有higher precedence 而不是字符串,所以+ 运算符当然希望在添加之前将您的字符串转换为数字。

你可以这样做:

print 'There are ' + CONVERT(varchar(10),@Number) +
      ' alias combinations did not match a record'

或使用RAISERROR 的(相当有限的)格式化工具:

RAISERROR('There are %i alias combinations did not match a record',10,1,@Number)
WITH NOWAIT

【讨论】:

  • 感谢您提供背景信息。我没有意识到 T-SQL 在执行简单的打印语句时有这么多的优先考虑。
  • @AdamJ - 这与print 语句本身无关。 T-SQL 是一种非常简单、非常老式的语言。在 T-SQL 中,运算符的所有输入都必须属于同一类型。
  • 谢谢!我想我有时会忘记 SQL 是在 70 年代创建的。 SQL Server 的外观相当时尚(在我看来),我认为这使它看起来比实际更现代。
【解决方案3】:

您不能组合字符串和数字字符串。您需要使用 CONVERT 或 CAST 将数字转换为字符串。

例如:

print 'There are ' + cast(@Number as varchar) + ' alias combinations did not match a record'

print 'There are ' + convert(varchar,@Number) + ' alias combinations did not match a record'

【讨论】:

    【解决方案4】:

    仔细检查您是否为要打印的 int 和 decimal 值设置了 初始值

    此示例正在打印一个空行

    declare @Number INT
    print 'The number is : ' + CONVERT(VARCHAR, @Number)
    

    这个样本正在打印 -> 数字是:1

    declare @Number INT = 1
    print 'The number is : ' + CONVERT(VARCHAR, @Number)
    

    【讨论】:

      【解决方案5】:

      如果您不想手动转换类型,可以使用CONCAT-function

      PRINT CONCAT('There are ', @Number, ' alias combinations did not match a record')
      

      【讨论】:

        【解决方案6】:

        你可以试试这个,

        declare @Number INT = 5                            
        print 'There are ' + CONVERT(VARCHAR, @Number) + ' alias combinations did not match a record'
        

        【讨论】:

          猜你喜欢
          • 2016-12-10
          • 2013-06-13
          • 2015-12-30
          • 2013-03-13
          • 1970-01-01
          • 2012-12-12
          • 2016-07-13
          相关资源
          最近更新 更多