How to trim everything after certain character in sql - sql-server

I am trying to format the email address in my table by removing everything starting the #. Also I would like to replace the underscore with blank space.
For example:
FirstName_LastName#gmail.com
I would like the above email to be changed like this:
FirstName LastName
Here is my code but this trims everything after the # and that is what i want. But how can i replace the underscore with blank. I want all in one statement using the update function. How can I do that?
SELECT
left (Email, CHARINDEX('#',Email)-1)
FROM [Dashboard]
Thanks for the help

SELECT REPLACE(LEFT(Email, CHARINDEX('#',Email)-1),'_',' ')
FROM [DSR].[dbo].[RCA_Dashboard]

This can be helpful if you need to remove all after the last certain character:
Declare #String nvarchar(max) =
'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\log.ldf'
select reverse(substring(reverse (#String), CHARINDEX('\', reverse (#String))+1, len(reverse (#String))));

Related

SQL Server : RTRIM not working to remove empty spaces

One of the column values in my tables have empty space at the end of each string.
In my select query, I am trying to trim the empty space at the end of string but the value is not getting trimmed.
SELECT
EmpId, RTRIM(Designation) AS Designation, City
FROM
tblEmployee
This is not trimming the empty space, not just this even the LTRIM(RTRIM(Designation) AS Designation is not working.
I also tried
CONVERT(VARCHAR(56), LTRIM(RTRIM(Designation))) AS [Designation]
Nothing is trimming the empty space at the end of the string...
Any help appreciated
EDIT
Thanks to suggestions in the comments, I checked what the last value was in the column using ASCII(). It is 160 is a non-breaking space.
How can I remove this non-breaking space?
How can I remove this non-breaking space?
Just replace it with '' and use CHAR() function as
SELECT REPLACE(YourColumn, CHAR(160), '')
FROM YourTable;
Since the value can contain non-breaking spaces you need to replace those with regular spaces before doing the trim:
SELECT
EmpId, RTRIM(REPLACE(Designation,char(160),' ')) AS Designation, City
FROM
tblEmployee
I faced the similar problem, Use below script to remove the space in case trim function not work -
SELECT LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE([ColumnName], CHAR(10),
CHAR(32)),CHAR(13), CHAR(32)),CHAR(160), CHAR(32)),CHAR(9),CHAR(32))))
FROM [TableName]
For more info visit this page - http://www.ashishblog.com/trim-not-removing-spaces-in-sql/

How do I remove line feed characters when selecting data from SQL Server?

I insert data that contains a line feed character into the database. Then I retrieve that data. I am using this script to attempt to remove the line feed while selecting the data from SQL:
Select Replace(Replace stringname,char(10),'',char(32),'')) from tablename
The replace function seems to execute, but it does not remove the line feed correctly.
The syntax of your statment looks wrong, maybe you can try with something like this:
Select Replace(Replace(#str,CHAR(10),''),CHAR(13),'')
The inner replace relaces LF and the outer replace replace CR
Shouldn't it be Select Replace(Replace(stringname,char(10),''),char(13),'') from tablename?
Also you could use single replace Select Replace(stringname,char(13)+char(10),'') from tablename.
char(32) corresponds to a space symbol
(select Replace( (select REPLACE( ColName,CHAR(10),'')),char(13),''))
as ColAlias
from YourTable
Solved with following .
I had issues with in sql data which even can not be seen as well in sql, causing me problem in some jquery functions.
A line feed is CHAR(10); a carriage return is CHAR(13).
The following code will remove a line feed characters and replaces it with a zero-length string:
UPDATE Table_Name SET Field_Name = REPLACE(Field_Name,CHAR(10),'');
If you want remove CRLF from the end of a string you can use RTRIM in postgresql.
for update operation:
UPDATE tablename
SET columnname = RTRIM(RTRIM(columnname,chr(10)),chr(13))
WHERE columnname like '%' || chr(13) or columnname like '%' || chr(10)
or for select:
SELECT RTRIM(RTRIM(columnname,chr(10)),chr(13)) FROM tablename
if you want leading or both use LTRIM or BTRIM

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

I'm in the process of trying to clear out leading and trailing spaces from an NVARCHAR(MAX) column that is filled with prices (using NVARCHAR due to data importing from multiple operating systems with odd characters).
At this point I have a t-sql command that can remove the leading/trailing spaces from static prices. However, when it comes to leveraging this same command to remove all prices, I'm stumped.
Here's the static script I used to remove a specific price:
UPDATE *tablename* set *columnname* = LTRIM(RTRIM(2.50)) WHERE cost = '2.50 ';
Here's what I've tried to remove all the trailing spaces:
UPDATE *tablename* set *columnname* LIKE LTRIM(RTRIM('[.]')) WHERE cost LIKE '[.] ';
I've also tried different varations of the % for random characters but at this point I'm spinning my wheels.
What I'm hoping to achieve is to run one simple command that takes off all the leading and trailing spaces in each cell of this column without modifying any of the actual column data.
To remove spaces from left/right, use LTRIM/RTRIM. What you had
UPDATE *tablename*
SET *columnname* = LTRIM(RTRIM(*columnname*));
would have worked on ALL the rows. To minimize updates if you don't need to update, the update code is unchanged, but the LIKE expression in the WHERE clause would have been
UPDATE [tablename]
SET [columnname] = LTRIM(RTRIM([columnname]))
WHERE 32 in (ASCII([columname]), ASCII(REVERSE([columname])));
Note: 32 is the ascii code for the space character.
To remove spaces... please use LTRIM/RTRIM
LTRIM(String)
RTRIM(String)
The String parameter that is passed to the functions can be a column name, a variable, a literal string or the output of a user defined function or scalar query.
SELECT LTRIM(' spaces at start')
SELECT RTRIM(FirstName) FROM Customers
Read more: http://rockingshani.blogspot.com/p/sq.html#ixzz33SrLQ4Wi
LTrim function and RTrim function :
The LTrim function to remove leading spaces and the RTrim
function to remove trailing spaces from a string variable.
It uses the Trim function to remove both types of spaces.
select LTRIM(RTRIM(' SQL Server '))
output:
SQL Server
I understand this question is for sql server 2012, but if the same scenario for SQL Server 2017 or SQL Azure you can use Trim directly as below:
UPDATE *tablename*
SET *columnname* = trim(*columnname*);
SELECT RTRIM(' Author ') AS Name;
Output will be without any trailing spaces.
Name
——————
‘ Author’
The LTrim function to remove leading spaces and the RTrim function to remove trailing spaces from a string variable.
It uses the Trim function to remove both types of spaces and means before and after spaces of string.
SELECT LTRIM(RTRIM(REVERSE(' NEXT LEVEL EMPLOYEE ')))

line breaks lost in sql server

I am entering error information into an ErrorLog table in my database. I have a utility class to do this:
ErrorHandler.Error("Something has broken!!\n\nDescription");
This works fine. However, when I try to access this table, the line breaks no longer seem to be present.
If I SELECT the table:
SELECT * from ErrorLog ORDER BY ErrorDate
there are no line breaks present in the log. This is kind of expected, as line breaks in one-line rows would break the formatting. However, If I copy the data out, the line break characters have been lost, and the data is all on one line.
How do I get line breaks in data at the end of my query when I put line breaks in? I don't know if the string has been stripped of line breaks when it enters the table, or if the viewer in SQL Server Management Studio has stripped out the line breaks.
The data type of the column into which error messages are put is nvarchar(Max), if that makes a difference.
EDIT: Unexpectedly, Pendri's solution didn't work.
Here is an excerpt of the string just before it passes into the SQL server:
POST /ipn/paymentResponse.ashx?installation=272&msgType=result HTTP/1.0\n\rContent-Length: 833\n\rContent-Type:
And here is the same string when I extract it from the grid viewer in SQL Server Management Studio:
POST /ipn/paymentResponse.ashx?installation=272&msgType=result HTTP/1.0 Content-Length: 833 Content-Type:
The place where the line break should be has been double spaced.
Any ideas?
No need to replace string input\output, you need just pick up correct option:
Tools -> Options...
> Query Results
> SQL Server
> Results to Grid
set "Retain CR\LF on copy or save" to true.
And don't forget to restart your management studio!
according Charles Gagnon answer
SSMS replaces linebreaks with spaces in the grid output. If you use Print to print the values (will go to your messages tab) then the carriage returns will be displayed there if they were stored with the data.
Example:
SELECT 'ABC' + CHAR(13) + CHAR(10) + 'DEF'
PRINT 'ABC' + CHAR(13) + CHAR(10) + 'DEF'
The first will display in a single cell in the grid without breaks, the second will print with a break to the messages pane.
A quick and easy way to print the values would be to select into a variable:
DECLARE #x varchar(100);
SELECT #x = 'ABC' + CHAR(13) + CHAR(10) + 'DEF';
PRINT #x;
Update a couple years later.
As described here, one solution to preserve viewing linebreaks in SSMS is to convert the output to XML:
SELECT * FROM (
SELECT * from ErrorLog ORDER BY ErrorDate
) AS [T(x)] FOR XML PATH
Fortunately, if you have SSMS 2012, this is no longer an issue, as line breaks are retained.
I echo David C's answer, except you should use the "TYPE" keyword so that you can click to open the data in a new window.
Note that any unsafe XML characters will not work well with either of our solutions.
Here is a proof of concept:
DECLARE #ErrorLog TABLE (ErrorText varchar(500), ErrorDate datetime);
INSERT INTO #ErrorLog (ErrorText, ErrorDate) VALUES
('This is a long string with a' + CHAR(13) + CHAR(10) + 'line break.', getdate()-1),
('Another long string with' + CHAR(13) + CHAR(10) + '<another!> line break.', getdate()-2);
SELECT
(
SELECT ErrorText AS '*'
FOR XML PATH(''), TYPE
) AS 'ErrorText',
ErrorDate
FROM #ErrorLog
ORDER BY ErrorDate;
I can confirm that the line breaks are preserved when copying out of a grid in SSMS 2012.
try using char(13) + char(10) instead of '\n' in your string (define a constant and concatenate to your sql)
Another simple solution is to click the "results to text" button in SSMS. Its not super clean, but gives you visibility to line breaks with about half a second of work.
For SQL Server 2008, there is no provision to set "Retain CR\LF on copy or save" to true.
For this issue, what I did is that, replace char(13) with "\r" and replace char(10) with "\n" like below.
REPLACE(REPlACE([COLUMN_NAME],char(13), '\r'),CHAR(10),'\n')
And in the code-behind again I've replaced "\r\n" with a break tag.
I worked out in this way as there was no option provided in SQL 2008 as mentioned above. This answer might be an alternative though.
Thanks

Getting at string data in SQL

I have a row entry with the following format:
Site=[number];this=that;foo=bar;
[number] above can be from 1...infinity. So I need to split out the [number] to use in another select statements where clause. Site=[number] is always at the beginning in the string and the data is always separated by a semi-colon.
declare #t nvarchar(100) = 'Site=230;this=that;foo=bar;';
select convert(int, substring(#t,6, charindex(';',#t,0)-6))
SELECT SUBSTRING(col, 1, CHARINDEX(col,';'))
Why are you storing data in the database in this format? Split it up into columns so that you can do meaningful queries.
You can play with the string this way:
declare #tx as nvarchar(100)
set #tx = 'Site=[number];this=that;foo=bar;'
print substring(
#tx,
CHARINDEX('[', #tx)+1,
CHARINDEX(']',#tx)-CHARINDEX('[',#tx)-1)
Hope this helps.
I don't have MS Sql Server available to try this out, but have you tried something like
Select
field
convert(bigint, substring(field, 6)) as thenum
from
thetable
where
condition=something
where field is the name of the field containing site=[number];...
The theory goes that substring will strip off site= off the beginning, and convert
will (hopefully) convert the number portion and ignore the rest of the text from the semicolon onwards.
It may or may not work. If not you may need to write an elaborate function instead.

Resources