简体   繁体   中英

sql server table values differ by space

I am running queries that total values and group based on value of another column, in this case that column being ITEM.

In the results I find that ITEM is sometimes returned twice for certain values thus causing the totals to be incorrect. Looking at the individual values I found the values to be:
'20' and ' 20' . Now I tried updating the table and removing all leading and trailing spaces but it does not seem to have helped. Any ideas>

update TableA
set item = ltrim(rtrim(item))

and the totals results show

   item    count
   20      2000
     3     1000
     20    500
   3       2000
   34      5999

how can i change this.

You could run something like this:

CREATE FUNCTION dbo.LTrimX(@str VARCHAR(MAX)) RETURNS VARCHAR(MAX) AS
BEGIN
    DECLARE @trimchars VARCHAR(10)
    SET @trimchars = CHAR(9)+CHAR(10)+CHAR(13)+CHAR(32)

    IF @str LIKE '[' + @trimchars + ']%'
        SET @str = SUBSTRING(@str, PATINDEX('%[^' + @trimchars + ']%', @str), 8000)
    RETURN @str
END
GO

CREATE FUNCTION dbo.RTrimX(@str VARCHAR(MAX)) RETURNS VARCHAR(MAX) AS
BEGIN
    DECLARE @trimchars VARCHAR(10)
    SET @trimchars = CHAR(9)+CHAR(10)+CHAR(13)+CHAR(32)
    IF @str LIKE '%[' + @trimchars + ']'
        SET @str = REVERSE(dbo.LTrimX(REVERSE(@str)))
    RETURN @str
END
GO

CREATE FUNCTION dbo.TrimX(@str VARCHAR(MAX)) RETURNS VARCHAR(MAX) AS
BEGIN
    RETURN dbo.LTrimX(dbo.RTrimX(@str))
END
GO


/* Perform Update */
UPDATE TableA SET item = dbo.TrimX(item)
GO 

if all of your "item" values are integers, with no leading zeros, you can do this:

update TableA set item = convert(int,item)

or even something like this:

update TableA set item=convert(int,item) WHERE item like '%20' or item like '%3'

First try finding the ascii value for the items

SELECT ITEM, ASCII(ITEM)
FROM TABLEA

Then do the update with the where clause

UPDATE TableA 
SET item = ltrim(rtrim(item))
WHERE ascii(item) = --Put the ascii value of the item that you want to update like 32 or 50 or 49 etc

If you have many item then you can use a cursor to loop through.
Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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