T-SQL 结果不足 space 无法将 uniqueidentifier 值转换为 char

T-SQL Insufficient result space to convert uniqueidentifier value to char

我该如何解决这个错误?

代码

declare @guid uniqueidentifier = '4164980A-EFD0-4C60-A18A-253465E00E9C'

print 'GUID ='+cast(@guid as varchar)

结果

Msg 8170, Level 16, State 2, Line 2
Insufficient result space to convert uniqueidentifier value to char.

您需要为 varchar 变量指定字符串长度,否则默认长度将为 30(长度不足以包含您的值),根据 Microsoft 文档 here

varchar [ ( n | max ) ] Variable-length, non-Unicode string data. n defines the string length and can be a value from 1 through 8,000.

When n is not specified when using the CAST and CONVERT functions, the default length is 30.

所以以下应该可以解决您的问题:

declare @guid uniqueidentifier = '4164980A-EFD0-4C60-A18A-253465E00E9C'
print 'GUID ='+cast(@guid as varchar(36))