remove spaces in the columns in ASE - sybase

I have columns that contain empty spaces with the data:
example:| fish |
how can I update the column so my result will be : |Fish| ?
in oracle I can trim the column:
update Example set column1 = trim(column1)
I google it and i notice that ASE doesnt supoort trim.

I found that str_replace(column1, ' ', '') does not actually replace the spaces.
Switching the '' for null works:
create table Example (column1 varchar(15))
insert into Example (column1) values ('| fish |')
select * from Example
-- produces "| fish |"
update Example set column1 = str_replace(column1, ' ', null)
select * from Example
-- produces "|fish|"
drop table Example

You can use combine of rtrim and ltrim
update Example set column1 = rtrim(ltrim(column1))
or str_replace
update Example set column1 = str_replace(column1,' ','')

Related

SQL Server CONCAT adds blank spaces when used

I've tried to use CONCAT function of some fields in a table; in order to get a string that I need to compare onto another field from different table.
However when I use the function it's like it random adds spaces between the fields and then I cannot use this result to compare.
I've tried:
SELECT CONCAT([STC_GL-STC].[ZZGL_Desc_Group_5D],'-',
[STC_GL-STC].[ZZCostCentreGroup],'-',
AS RESULT
FROM [STC_GL-STC];
As an example of result:
'Compras - RM -MATERIA PRIMA -'
(Please note the blank spaces in the second and third (-).
I would need to obtain:
'Compras - RM-MATERIA PRIMA-'
I've checked the values in the fields and there is no blank spaces at the end on fields ZZGL_Desc_Group_5D , ZZCostCentreGroup.
I've also tried:
SELECT CONCAT_WS('-',[ZZGL_Desc_Group_5D],[ZZCostCentreGroup]) AS RESULT
FROM [STC_GL-STC]
With same result.
And finally I tried to remove blank spaces using RTRIM and LTRIM using the following:
SELECT CONCAT(LTRIM(RTRIM([STC_GL-STC].[ZZGL_Desc_Group_5D])),
LTRIM(RTRIM('-')),
LTRIM(RTRIM([STC_GL-STC].[ZZCostCentreGroup]))) AS RESULT
FROM [STC_GL-STC]
ORDER BY RESULT ASC;
And even with LTRIM and RTRIM functions on that field, I still getting the same result.
How to get rid of this behaviour and of the blank spaces? Is there another way to build that string?
Kind Regards and many thanks in advance,
Long time ago I created a udf function to remove white spaces.
It is based on the 'magic' of the XML xs:token data type.
udf
/*
1. All invisible TAB, Carriage Return, and Line Feed characters will be replaced with spaces.
2. Then leading and trailing spaces are removed from the value.
3. Further, contiguous occurrences of more than one space will be replaced with a single space.
*/
CREATE FUNCTION dbo.udf_tokenize(#input VARCHAR(MAX))
RETURNS VARCHAR(MAX)
AS
BEGIN
RETURN (SELECT CAST('<r><![CDATA[' + #input + ']]></r>' AS XML).value('(/r/text())[1] cast as xs:token?','VARCHAR(MAX)'));
END
Test harness
-- DDL and sample data population, start
DECLARE #mockTbl TABLE (ID INT IDENTITY(1,1), col_1 VARCHAR(100), col_2 VARCHAR(100));
INSERT INTO #mockTbl (col_1, col_2)
VALUES (' FL ', ' Miami')
, (' FL ', ' Fort Lauderdale ')
, (' NY ', ' New York ')
, (' NY ', '')
, (' NY ', NULL);
-- DDL and sample data population, end
SELECT *
, col_1n = dbo.udf_tokenize(col_1)
, col_2n = dbo.udf_tokenize(col_2)
, CONCAT_WS('-', dbo.udf_tokenize(col_1), dbo.udf_tokenize(col_2)) AS RESULT
FROM #mockTbl;

Update SQL Query for varchar(max) column

How to update a varchar(max) column to an empty string from null value?
Here is the pseudo code:
UPDATE tablename
SET all varchar(max) columns =''
WHERE varchar(max) == NULL
Need to create something like this, any help will be appreaciated!
Please use this. where ColumnName IS NULL for NULL comparison equal does not work with default ANSI_NULLS.
ColumnName -> VARCHAR(MAX)
Update tablename
SET field =''
where ColumnName IS NULL
Regarding this question, When you gonna Update the column try to put the empty string inside the quotes
You can check this code hopefully you will get the Idea
UPDATE Table_Name (v VARCHAR(4))
SET (' ')
WHERE condition;
Output
SELECT CONCAT ('(', v, ')') FROM Table_Name;
| CONCAT('(', v, ')')
| ( )
In order to UPDATE to all row which has null values use ANSI SQL COALESCE() function
UPDATE tablename
SET
Column = COALESCE(Column, ''), Column1 = COALESCE(Column1, ''),
....
Column4 = COALESCE(Column4, '')
Since use of COALESCE(), it would just update the column values to blank where it found the null values.

How can I CUT a specific string part to another column in SQL?

I have about 500 records in a table with an nvarchar column.
I want to cut a part of that data into another column. by "cut" I mean deleting it in the original column and add it to the target column.
All the data that has to be cut is contained within brackets. The bracketed text may occur anywhere in the string.
For example, ColumnA has: SomeTest Data [I want to cut this], and I want to move [I want to cut this] (but without the brackets) to ColumnB.
How do I achieve this?
UPDATE
Eventually found it out. The problem was that I didn't escaped my brackets.
What I have now (and works):
UPDATE TableA
SET TargetColumn = substring(SourceColumn,charindex('[',SourceColumn)+1,charindex(']',SourceColumn)-charindex('[',SourceColumn)-1),
SourceColumn = substring(SourceColumn, 0, charindex('[',SourceColumn))
where TableA.SourceColumn like '%\[%\]%' ESCAPE '\'
An UPDATE statement along these lines would do it:
CREATE TABLE #Test
(
StringToCut VARCHAR(100)
,CutValue VARCHAR(100)
)
INSERT #Test
VALUES
('SomeTest Data 1 [I want to cut this 1] More Testing',NULL),
('SomeTest Data 2 [I want to cut this 2]',NULL),
('SomeTest Data 3 [I want to cut this 3] Additional Test',NULL),
('[I want to cut this 4] last test',NULL)
SELECT * FROM #Test
--Populate CutValue column based on starting position of '[' and ending position of ']'
UPDATE #Test
SET CutValue = SUBSTRING(StringToCut,CHARINDEX('[',StringToCut),(CHARINDEX(']',StringToCut)-CHARINDEX('[',StringToCut)))
--Remove the '[' ']'
UPDATE #Test
SET CutValue = REPLACE(CutValue,'[','')
UPDATE #Test
SET CutValue = REPLACE(CutValue,']','')
--Remove everything after and including '[' from StringToCut
UPDATE #Test
SET StringToCut = LEFT(StringToCut,CHARINDEX('[',StringToCut)-1) + LTRIM(RIGHT(StringToCut,LEN(StringToCut)-CHARINDEX(']',StringToCut)))
SELECT * FROM #Test
DROP TABLE #Test
You left some questions unanswered.
How do you want to handle NULL values? I am leaving them NULL.
Where should the 'cut' string go? I am assuming "at the end"
What do you do if you find nested brackets? [[cut me]]
Do you need to remove any surrounding spaces? For example, does "The cat [blah] sleeps" become "The cat**sleeps" with two spaces before "sleeps"?
To make the operation atomic, you'll want to use a single UPDATE.
Here is a sample script to get you started.
--build a temp table with sample data
declare #t table(ikey int, sourcecolumn nvarchar(100), targetcolumn nvarchar(100));
insert into #t
select 0,'SomeTest Data [I want to cut this]','Existing Data For Row 1'
union select 1,'SomeTest [cut this too] Data2','Existing Data For Row 2'
union select 2,'[also cut this please] SomeTest Data3',null
union select 3,null,null
union select 4,null,''
union select 5,'Nested bracket example [[[within nested brackets]]] Other data',null
union select 6,'Example with no brackets',null
union select 7,'No brackets, and empty string in target',''
--show "before"
select * from #t order by ikey
--cut and paste
update #t
set
targetcolumn =
isnull(targetcolumn,'') +
case when 0 < isnull(charindex('[',sourcecolumn),0) and 0 < isnull(charindex(']',sourcecolumn),0)
then substring(sourcecolumn,charindex('[',sourcecolumn)+1,charindex(']',sourcecolumn)-charindex('[',sourcecolumn)-1)
else ''
end
,sourcecolumn =
case when sourcecolumn is null
then null
else substring(sourcecolumn,0,charindex('[',sourcecolumn)) + substring(sourcecolumn,charindex(']',sourcecolumn)+1,len(sourcecolumn))
end
where sourcecolumn like '%[%'
and sourcecolumn like '%]%'
--show "after"
select * from #t order by ikey
And another one in single update statement -
CREATE TABLE #Test
(
StringToCut VARCHAR(50)
,CutValue VARCHAR(50)
)
INSERT #Test
VALUES
('SomeTest Data 1 [I want to cut this 1]',NULL),
('SomeTest Data 2 [I want to cut this 2]',NULL),
('SomeTest Data 3 [I want to cut this 3]',NULL),
('SomeTest Data 4 [I want to cut this 4]',NULL)
UPDATE #Test
SET CutValue =
SUBSTRING(StringToCut, CHARINDEX('[', StringToCut)+1, CHARINDEX(']', StringToCut) - CHARINDEX('[', StringToCut) - 1)
SELECT * FROM #Test

How to convert empty spaces into null values, using SQL Server?

I have a table and the columns on this table contains empty spaces for some records. Now I need to move the data to another table and replace the empty spaces with a NULL value.
I tried to use:
REPLACE(ltrim(rtrim(col1)),' ',NULL)
but it doesn't work. It will convert all of the values of col1 to NULL. I just want to convert only those values that have empty spaces to NULL.
I solved a similar problem using NULLIF function:
UPDATE table
SET col1 = NULLIF(col1, '')
From the T-SQL reference:
NULLIF returns the first expression if the two expressions are not equal. If the expressions are equal, NULLIF returns a null value of the type of the first expression.
Did you try this?
UPDATE table
SET col1 = NULL
WHERE col1 = ''
As the commenters point out, you don't have to do ltrim() or rtrim(), and NULL columns will not match ''.
SQL Server ignores trailing whitespace when comparing strings, so ' ' = ''. Just use the following query for your update
UPDATE table
SET col1 = NULL
WHERE col1 = ''
NULL values in your table will stay NULL, and col1s with any number on space only characters will be changed to NULL.
If you want to do it during your copy from one table to another, use this:
INSERT INTO newtable ( col1, othercolumn )
SELECT
NULLIF(col1, ''),
othercolumn
FROM table
This code generates some SQL which can achieve this on every table and column in the database:
SELECT
'UPDATE ['+T.TABLE_SCHEMA+'].[' + T.TABLE_NAME + '] SET [' + COLUMN_NAME + '] = NULL
WHERE [' + COLUMN_NAME + '] = '''''
FROM
INFORMATION_SCHEMA.columns C
INNER JOIN
INFORMATION_SCHEMA.TABLES T ON C.TABLE_NAME=T.TABLE_NAME AND C.TABLE_SCHEMA=T.TABLE_SCHEMA
WHERE
DATA_TYPE IN ('char','nchar','varchar','nvarchar')
AND C.IS_NULLABLE='YES'
AND T.TABLE_TYPE='BASE TABLE'
A case statement should do the trick when selecting from your source table:
CASE
WHEN col1 = ' ' THEN NULL
ELSE col1
END col1
Also, one thing to note is that your LTRIM and RTRIM reduce the value from a space (' ') to blank (''). If you need to remove white space, then the case statement should be modified appropriately:
CASE
WHEN LTRIM(RTRIM(col1)) = '' THEN NULL
ELSE LTRIM(RTRIM(col1))
END col1
Maybe something like this?
UPDATE [MyTable]
SET [SomeField] = NULL
WHERE [SomeField] is not NULL
AND LEN(LTRIM(RTRIM([SomeField]))) = 0
here's a regex one for ya.
update table
set col1=null
where col1 not like '%[a-z,0-9]%'
essentially finds any columns that dont have letters or numbers in them and sets it to null. might have to update if you have columns with just special characters.

How do I trim these fields of quotation marks in SQL Server?

I have a table with 6 million + records, but the first field has a " at beginning and the last field has " at the end
i guess when doing a bulk insert they forgot to remove it.
I want to run an update query which will remove the " from those 2 fields
Sample data -
Field 1
"18157142
"18157152
"18157159
"18157177
"18157189
"18157191
"18157197
"18157208
"18157223
"18157224
Field 2 (Last field)
243901"
832218"
506356"
78301"
753201 - Automobile Body"
553111 - Automobile Parts & Supplies-Retail"
581203"
792903 - Music"
653118"
541105 - Grocers"
Also no place in this field does the " show up anywhere else so its just 1 " to remove from the field.
Any ideas?
Update myTable
SET
Field1 = Replace(Field1, '"', ''),
Field2 = Replace(Field2, '"', '')
This would work faster than other recommendations because you won't have to perform any extra string length function calls to determine how far over to count. This will just replace all occurrences of the quotes, which is what was originally asked for (since quotes won't show up anywhere where they might not want to be removed).
This is the update,
update table
set field1 = right(field1,length(field1)-1),
field2 = left(field1,length(field1)-1)
The problem is the enormous transaction that it will generate...
UPDATE TableName
SET Field1 = MID(Field1,2)
Field2 = MID(Field2,1,LEN(Field2)-1)
UPDATE MyTable
SET Field1 = RIGHT(Field1, LEN(Field1) - 1), Field2 = LEFT(Field2, LEN(Field2) - 1)
UPDATE [table]
SET [field1] = RIGHT( [field1], LEN([field1]) - 1),
[field2] = LEFT( [field2], LEN([field2]) - 1)
If you have the time to wait I would just:
update [tableName] set field1 = right(field1, len(field1) -1)
update [tableName] set field2 = left(field2, len(field2) -1)

Resources