問題描述
此 SQL Server 2005 T-SQL 代碼:
This SQL Server 2005 T-SQL code:
DECLARE @Test1 varchar;
SET @Test1 = 'dog';
DECLARE @Test2 varchar(10);
SET @Test2 = 'cat';
SELECT @Test1 AS Result1, @Test2 AS Result2;
產生:
結果 1 = d結果 2 = 貓
我希望要么
- 賦值
SET @Test1 ='dog';
失敗,因為沒有@Test1
有足夠的空間 - 或者
SELECT
在 Result1 列中返回dog".
- The assignment
SET @Test1 = 'dog';
to fail because there isn't enough room in@Test1
- Or the
SELECT
to return 'dog' in the Result1 column.
@Test1
怎么了?有人可以解釋一下這種行為嗎?
What is up with @Test1
? Could someone please explain this behavior?
推薦答案
讓我用 SQL Server 文檔中的一些引述來回答.
Let me answer with some quotes from the SQL Server documentation.
char 和 varchar
varchar[(n)]
...
當數據定義或變量聲明語句中未指定 n 時,默認長度為 1.
When n is not specified in a data definition or variable declaration statement, the default length is 1.
轉換字符數據
當字符表達式轉換為不同大小的字符數據類型時,對于新數據類型來說太長的值將被截斷.
When character expressions are converted to a character data type of a different size, values that are too long for the new data type are truncated.
因此,您的 varchar 被聲明為 varchar(1)
,并且您的 SET
語句中的隱式轉換(從長度為 3 的字符串文字到 varchar(1)
) 將 dog
截斷為 d
.
So, your varchar is declared as a varchar(1)
, and the implicit conversion in your SET
statement (from a string literal of length 3 to a varchar(1)
) truncates dog
to d
.
這篇關于SQL Server 2005 奇怪的 varchar 行為的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!