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>
up开发者_如何学编程date 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.
精彩评论