SQL Server 2012 :: Replacing Recurring Characters In A String With Single Character
Jan 20, 2014
I have a problem where I want to write a function to remove recurring characters from a string and replace them with a single same character.
For instance I have the string '12333345566689' and the result should be '12345689'. In Oracle I could do this with "regexp_replace('12333345566689', '(.)1+', '1')", but in T-SQL the only solution I could think of is something like this:
DECLARE @code NVARCHAR(255)
SET @code = '12333345566689';
SET @code = REPLACE(REPLACE(REPLACE(@Code, '1', '~1'), '1~', ''), '~1', '1');
and repeat this for 2 - 9. But I'm sure there is a more elegant version for this in SQL Server 2012.
I'm trying to replace a particular part of a row in a table with a new value.
The row is called "DataPath" and it has a lot of values like so:
mashOperationsComponent Data FilesSantec
I want to run a query to replace the mash with our DFS namespace share name companysharesDepartments but keep everything else past the mash part of the original row.
I'm currently running this query, it says it is altering 30,000 rows, but it doesn't look like it's doing anything at all..
UPDATE dbo.Part SET DataPath = REPLACE(DataPath,'company.localsharesDepartments','mash') WHERE DataPath like 'mash\%'
So for example, it would change the mash above to
company.localsharesDepartmentsOperationsComponent Data FilesSantec
I am trying to replace all special characters in a column with one special character.
Example:
Table: dbo.Employee Column: Name Name ------- edwardneuman!"<] mikemoreno)'>$: JeffJensen"?>"
I am trying to get the namepart to the left of ANY special character. To achieve this, I am thinking of replacing all the special characters with a single special character so that I can find the first occurrence of that special character and grab left of the special character (SUBSTRING/CHARINDEX). This way I don't need to loop through all the special characters.
I am expecting the following results:
Name ------- edwardneuman<<<< mikemoreno<<<<< JeffJensen<<<<
I need extracting string that is between certain characters that are in certain position.
Here is the DDL:
DROP TABLE [dbo].[StoreNumberTest] CREATE TABLE [dbo].[StoreNumberTest]( [StoreNumber] [varchar](50) NULL, [StoreNumberParsed] [varchar](50) NULL) INSERT INTO [dbo].[StoreNumberTest]
[Code] ....
What I need to accomplish is to extract the string that is between the third and fifth '-' (dash) and insert it into the StoreNumberParsed while eliminating the fourth dash.
Sample output would be:
KY117 CA132 OH174 MD163 FL191
I know that parse, charindex, patindex all might come in play, but not sure how to construct the statement.
I am trying to count the characters in a sting before a space. Here is the example of what I am trying to accomplish.
"2073 9187463 2700' 4 7 4, the string character count is 4 before the space, 7 is the count before the next space and the last is the last in the string, if there was more characters within this string for example....'2073 9187463 2700 7023 6044567' it would return the number of characters in the string before the space and at the very end of it.
I am looking for the fastest way to strip non-numeric characters from a string.
I have a user database that has a column (USER_TELNO) in which the user can drop a telephone number (for example '+31 (0)12-123 456'). An extra computed column (FORMATTED_TELNO) should contain the formatted telephone number (31012123456 in the example)
Note: the column FORMATTED_TELNO must be indexed, so the UDF in the computed column has WITH SCHEMABINDING.... I think this implicates that a CLR call won't work....
I have a varchar field which contains some Greek characters (α, β, γ, etc...) among the regular Latin characters. I need to replace these characters with a word (alpha, beta, gamma etc...). When I try to do this, I find that it is also replacing some of the Latin characters.
Create table DBInfo (Path varchar (500)) Insert into DBInfo values('/Data Sources') Insert into DBInfo values('/Data Sources/SALES') Insert into DBInfo values('/PRODUCTION') Insert into DBInfo values('/PRODUCTION/SERVICE') Insert into DBInfo values('/PRODUCTION/SERVICE/MAINTENANCE') Insert into DBInfo values('/PRODUCTION/SERVICE/LOGISTICS')
My Expected Output
Column1,Column2,Column3 Data SourcesNullNull Data SourcesSalesNull PRODUCTIONNullNull PRODUCTIONSERVICENull PRODUCTIONSERVICEMAINTENANCE PRODUCTIONSERVICELOGISTICS
How to retrieve all possible sets of values from a table, with each set having a unique identifier.
Here's sample data, where any number of rows can be in the "animal" set:
select animal.name from ( select 'Cat' as name union all select 'Dog' union all select 'Bird' ) animalHere's what I'm trying to get:
[Code] ....
It'd be an easy task if I knew how many rows were in the set, but without knowing how many (and being able to do x number of cross joins and CUBE/ROLLUP to produce the list of permutations) or writing a horrid complex of while loops, I'm at a loss.
A single column. All permutations of the values in a single column. Perhaps I should stay off here nearer the end of the day .
I have an Address column that I need to Substring. I want to remove part of the string after either, or both of the following characters i.e ',' OR '*'
Example Record 1. Elland **REQUIRES BOOKING IN*** Example Record 2. Theale, Nr Reading, Berkshire Example Record 3. Stockport
How do I achieve this in a CASE Statement?
The following two case statements return the correct results, but I some how need to combine them into a single Statement?
,LEFT(Address ,CASE WHEN CHARINDEX(',',Address) =0 THEN LEN(Address ) ELSE CHARINDEX(',' ,Address ) -1 END) AS 'Town Test'
,LEFT(Address ,CASE WHEN CHARINDEX('*',Address ) =0 THEN LEN(Address) ELSE CHARINDEX('*' ,Address ) -1 END) AS 'Town Test2'
My requirement is that if the string in the column has any of the characters from 'ACDIPFJZ' , those characters have to be retained and the rest of the characters have to be removed.
I usually do this through Access so I'm not too familiar with the string functions in SQL. My question is, how do you remove characters from the middle of a string?
Ex: String value is 10 characters long. The string value is X000001250. The end result should look like, X1250.
I've tried mixing/matching multiple string functions with no success. The only solution I have come up with removes ALL of the zeros, including the tailing zero. The goal is to only remove the consecutive zeroes in the middle of the string.
I have a table with column type as ntext. I need to modify the column value. I wanted to replace a given characterstring with another one in this column. Any assistance on this is highly appreciated.
I am incorporating a perl script loading data into my SQL Server. If I receive a message with a single backslash I know to replace it with a double backslash \. But what if it is a " double quote what do I need to do to get it to appear as is?
ive been working on this script today and cannot for the life of me get the following employee name format correct...
the data is currently "lastname~firstname" in employee table... i am trying to write a select statement that will take that and remove the "~" (tilde) and replace it with a "," (comma).
how do i get "lastname~firstname" from employee table to display in "lastname,firstname" format?
i'm trying to figure out a way to replace a handful of "Illegal" characters in our SQL tables. We are using Project Server and some of these characters are causing errors or other issues in OLAP Cube.
I'm trying to figure out a way to change the following characters to an underscore ( _ ) :
illegal characters are: / ( ) . , ' : - &
Can I just create a SQL query that loops through a column to replace all of these characters at once? or do I have to replace one character at a time?! I tested replacing one at a time and it works with the REPLACE function.
I'm not all that familiar with MSSQL, I've spent past few years working with MySQL instead.
how can my query loop? or would using CASE help me out?
thanks. any feedback is much appreciated. If you need to know more, let me know.
I have a large table, tblMessage, which stores e-mail messages in textfields. I need to remove the carriage returns the data in these fields,but I have not yet figured out how to do so.I thought that the way to do this would be with the REPLACE function;unfortunately, of course, the REPLACE function cannot work with TEXTfields. I tried CASTing the text field to VARCHAR(8000); however, someof the rows have more than 8000 characters in the text field, so it bombs.Here is the SQL that I tried:selectmsgID,msgSent,msgFromType,msgFromID,msgSubject,REPLACE (CAST(msgMessage AS varchar(8000)), CHAR(13), '<BR>') ASnewMessage,msgOriginal,attIDinto tblMessageNewfrom tblMessageI'm at my wit's end. Truncating the text field to 8000 character is anacceptable option, but I can't even seem to be able to do that.I'm using SQL Server version 7.
Hi,I come from the "dark side" php/mysql and there often problems withcharacter sets (utf-8, latin...) and storing data in datebase.Exists in the world of dot.net and ms-sql-server similiar problems?To precise: I have to store xml-data in database. Maybe its better toencode (like base64) the strings?Perhaps there are some links to read?Thanks.klaus.
Hi, this is my second attempt to get an answer to this question. We want to strip our firstName column and lastname column of any punctuation that might be present. What's the best of doing that? Is my only choice to write a nested REPLACE for each character we want replaced (which will end up being very very long) or is there another way. thanks Zoey
When we are getting data in a table and we want to replace characters with other characters. For example, We have a table with a street address, and there are numerous ascii character values we want to review and replace if they exist. We were looking at using a table with 2 columns, 1 containing each ascii character value the other it's preferred replacement value. Then updating the street address searching through each ascii character and replacing it if needed. Currently, we are running it through a looping process searching each individual address for each ascii character, and updating it.
I have a fixed-width flat file. Within some of the rows, I have embedded NULL characters. The inherit problem is that NULL characters are string terminators, so using a flat file source doesn't allow the capturing of these NULL characters or any characters after the first NULL character -- only the string up to the NULL character.
So, within SSIS, what would be the best way to replace NULL characters with a SPACE character? My file is fixed-width, and replacing with a space will allow me to keep the length the same. I am not opposed to running a script task against the file first (before using my flat file source), but would need some guidance as I'm not a .Net guru, by any means.
Unfortunately, going to the bank to have them correct this file has proved fruitless. We're going to have to deal with these characters on our side.
I have records where there are multiple spaces between items of text. I would like to strip out all the excess spaces characters. To that end I have written to separate functions (both are listed below) neither of which I would imagine will be particularly efficient. The first uses an int table and the second a while loop. I am presently ignoring the leading and trailing space issue as this can easily be recitfied with LTRIM and RTRIM. However, I would be keen to know if there is a better way of achieving a similar result.
CREATE FUNCTION dbo.StripAdditionalSpaces (@Input varchar(1000)) RETURNS varchar(1000) AS BEGIN DECLARE @Changed int, @Output varchar(1000) SELECT @Output = '' DECLARE @String TABLE ([Output] varchar(1000)) INSERT INTO @String ([Output]) VALUES (@Input)
SELECT @Output = @Output + SUBSTRING([Output], i1.Position, 1) FROM @String LEFT JOIN dbo.Ints i1 ON SUBSTRING([Output], i1.Position, 1) <> ' ' or ISNULL(SUBSTRING([Output], i1.Position - 1, 1), '') <> ' ' RETURN @Output END GO CREATE FUNCTION dbo.StripAdditionalSpaces2 (@Input varchar(1000)) RETURNS varchar(1000) AS BEGIN DECLARE @Output varchar(1000) SELECT @Output = @Input
WHILE @Output LIKE '% %' BEGIN SELECT @Output = REPLACE(@Output, ' ' , ' ') END RETURN @Output END GO
I have a stored proc that contains an update which utilizes a case statement to populate values in a particular column in a table, based on values found in other columns within the same table. The existing update looks like this (object names and values have been changed to protect the innocent):
UPDATE dbo.target_table set target_column = case when source_column_1= 'ABC'then 'XYZ' when source_column_2= '123'then 'PDQ'
[Code] ....
The powers that be would like to replace this case statement with some sort of table-driven structure, so that the mapping rules defined above can be maintained in the database by the business owner, rather than having it embedded in code and thus requiring developer intervention to perform changes/additions to the rules.
The rules defined in the case statement are in a pre-defined sequence which reflects the order of precedence in which the rules are to be applied (in other words, if a matching value in source_column_1 is found, this trumps a conflicting matching value in source_column_2, etc). A case statement handles this nicely, of course, because the case statement will stop when it finds the first "hit" amongst the WHEN clauses, testing each in the order in which they are coded in the proc logic.
What I'm struggling with is how to replicate this using a lookup table of some sort and joins from the target table to the lookup to replace the above case statement. I'm thinking that I would need a lookup table that has column name/value pairings, with a sequence number on each row that designates the row's placement in the precedence hierarchy. I'd then join to the lookup table somehow based on column names and values and return the match with the lowest sequence number, or something to that effect.
I am trying to insert some values retrieved from textboxes into an Access DB using ASP.NET. When I try to run this code I get an error reading "Too many characters in character literal". What does this mean? Also, how do I break new lines, does way this look ok?