简体   繁体   English

在选择语句中使用修剪

[英]using trim in a select statement

I have a table, my_table , that has a field my_field . 我有一个表my_table ,其中有一个字段my_field myfield is defined as VARCHAR(7). myfield被定义为VARCHAR(7)。 When I do: 当我做:

SELECT myfield 
  FROM my_table;

I get what appears to be the entire 7 characters, but I only want the actual data. 我得到的似乎是整个7个字符,但我只需要实际数据。

I tried: 我试过了:

SELECT TRIM(myfield)
  FROM my_table;

and several variations. 和一些变化。 But instead of getting 'abcd', I get 'abcd '. 但是我没有得到“ abcd”,而是得到了“ abcd”。

How do I get rid of the trailing blanks? 如何摆脱尾随的空白?

As others have said: 正如其他人所说:

  • trim whitespace before data enters the database ("Mop the floor...); 在数据进入数据库之前修剪空格(“拖地板...”);
  • ensure this is not actually a column of type CHAR(7) . 确保这实际上不是CHAR(7)类型的列。

Additionally, add a CHECK constraint to ensure no trailing spaces ("...fix the leak.") While you are at it, also prevent leading spaces, double spaces and zero-length string eg 此外,添加CHECK约束以确保没有尾随空格(“ ...修复泄漏。”)。在使用时,还应防止前导空格,双倍空格和零长度字符串,例如

CREATE TABLE my_table
(
 myfield VARCHAR(7) NOT NULL    
    CONSTRAINT myfield__whitespace
       CHECK (
              NOT (
                   myfield = ''
                   OR myfield LIKE ' %'
                   OR myfield LIKE '% '
                   OR myfield LIKE '%  %'
                  )
             )
);-

VARCHAR columns will not pad the string you insert, meaning if you are getting 'ABCD ', that's what you stored in the database. VARCHAR列不会填充您插入的字符串,这意味着如果获取的是'ABCD',那就是您存储在数据库中的内容。 Trim your data before inserting it. 插入数据之前,请先对其进行整理。

Make sure you are not using the CHAR datatype, which will pad your data in the way you suggest. 确保您没有使用CHAR数据类型,它将以您建议的方式填充数据。 In any case: 任何状况之下:

SELECT TRIM(myfield) FROM mytable; 

will work. 将工作。

Make sure also that you are not confusing the way the SQL interpreter adds padding chars to format the data as a table with the actual response. 还请确保您不要混淆SQL解释器添加填充字符以将数据格式化为具有实际响应的表的方式。

确保您没有在CHAR(7)字段的此列中插入数据。

与插入时相比,选择时需要修剪结果,例如:

SELECT TRIM(myfield) FROM my_table;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM