3

我是 SQL 新手,想为 MS SQL Server (MS SQL Server 2012) 创建一些 UDF 函数,但非常简单的表达式不起作用。我只是想连接 2 个字符串并将结果保存到第一个:

DECLARE @ret   CHAR (20)
SET @ret = '4'
SET @ret = @ret + '55'

执行后,@ret保持在4! 为什么?如果我为“4”引入另一个变量,它会起作用。我怎样才能克服这个问题?

4

5 回答 5

3

那是因为您使用char数据类型。

当您将值存储'4'在 achar(20)中时,它变为'4___________________'(20 个字符长,_这里代表空格)。

当您连接'4___________________''55'获得'4___________________55'(22 个字符长)时。

当您将其存储回char(20)变量中时,它将被截断为 20 个字符,您将得到'4___________________'.

于 2012-09-06T17:10:31.737 回答
2

When you have a CHAR(20) the first SET will actually store '4' with 19 blank characters at the end. This is because the CHAR datatype is fixed width, and will pad your data with blank characters until it gets to the size, 20 here.

When you concatenate the '55' onto the end, it will be the 21st and 22nd characters in the string, and fall off when you try to store it inside @ret, which can only hold the first 20 characters.

Using an VARCHAR will solve your problem, allowing @ret to be the exact size you require.

DECLARE @ret VARCHAR(20);
SET @ret = '4';
SET @ret = @ret + '55';
于 2012-09-06T17:09:04.187 回答
1

更改变量的数据类型以匹配您要连接的内容:而不是 char 使用 varchar

于 2012-09-06T17:11:14.890 回答
1

As CHAR is a fixed length string data type, so any remaining space in the field is filled with blanks.

In your scenario, SET @ret = @ret + '55' will try to store 22 character but unfortunately, the variable is already declared as 20 character long so it truncated the result back to 20 character..Hence, you'll have 20 character with truncating last 2 character i.e. '55'.

Use char data type only when you are sure about the length of data which particular char data type column have to hold....

If you use nvarchar(20) instead of char(20), it will work fine...

DECLARE @ret   nvarchar (20)
SET @ret = '4'
SET @ret = @ret + '55'

See the SQLFIDDLE

于 2012-09-06T17:09:03.667 回答
0

尝试在你的函数中使用'cast'以确保@ret是一个字符串,将你的代码更改为这个工作;希望这可以帮助。

DECLARE @ret   CHAR (20)  
SET @ret = '4'   
SET @ret = cast(@ret as varchar(1)) + '55'  

或者只是将 CHAR(20) 更改为 NVARCHAR(20) ,如下所示:

DECLARE @ret   NVARCHAR (20)  
SET @ret = '4'   
SET @ret = @ret + '55'  
于 2012-09-06T17:09:51.933 回答