Replace some characters in a column - sql-server

I need to remove some characters and replace them from others.
Like in a column I need to replace
I need to replace column text from "data&data&sometext" to "data&sometext".
Something like
UPDATE TABLE
SET Column = "data&sometext"
WHERE Column = "data&data&sometext"

UPDATE TABLE
SET Column = REPLACE(Column , 'data&data&sometext', 'data&sometext')
WHERE Column LIKE '%data&data&sometext%'

Well, try this:
UPDATE TABLE
SET Column = REPLACE(Column, 'data&data&', 'data&')
WHERE Column LIKE 'data&data&%';
UPDATE:
So, based on your comment, try this:
UPDATE TABLE
SET Column = REPLACE([Column], LEFT([Column], CHARINDEX('&', [Column], CHARINDEX('&', [Column]) + 1)), LEFT([Column], CHARINDEX('&', [Column])))
WHERE Column LIKE LEFT([Column], CHARINDEX('&', [Column], CHARINDEX('&', [Column]) + 1)) + '%'

Related

Generate column name dynamically in sql server

Please look at the below query..
select name as [Employee Name] from table name.
I want to generate [Employee Name] dynamically based on other column value.
Here is the sample table
s_dt dt01 dt02 dt03
2015-10-26
I want dt01 value to display as column name 26 and dt02 column value will be 26+1=27
I'm not sure if I understood you correctly. If I'am going into the wrong direction, please add comments to your question to make it more precise.
If you really want to create columns per sql you could try a variation of this script:
DECLARE #name NVARCHAR(MAX) = 'somename'
DECLARE #sql NVARCHAR(MAX) = 'ALTER TABLE aps.tbl_Fabrikkalender ADD '+#name+' nvarchar(10) NULL'
EXEC sys.sp_executesql #sql;
To retrieve the column name from another query insert the following between the above declares and fill the placeholders as needed:
SELECT #name = <some colum> FROM <some table> WHERE <some condition>
You would need to dynamically build the SQL as a string then execute it. Something like this...
DECLARE #s_dt INT
DECLARE #query NVARCHAR(MAX)
SET #s_dt = (SELECT DATEPART(dd, s_dt) FROM TableName WHERE 1 = 1)
SET #query = 'SELECT s_dt'
+ ', NULL as dt' + RIGHT('0' + CAST(#s_dt as VARCHAR), 2)
+ ', NULL as dt' + RIGHT('0' + CAST((#s_dt + 1) as VARCHAR), 2)
+ ', NULL as dt' + RIGHT('0' + CAST((#s_dt + 2) as VARCHAR), 2)
+ ', NULL as dt' + RIGHT('0' + CAST((#s_dt + 3) as VARCHAR), 2)
+ ' FROM TableName WHERE 1 = 1)
EXECUTE(#query)
You will need to replace WHERE 1 = 1 in two places above to select your data, also change TableName to the name of your table and it currently puts NULL as the dynamic column data, you probably want something else there.
To explain what it is doing:
SET #s_dt is selecting the date value from your table and returning only the day part as an INT.
SET #query is dynamically building your SELECT statement based on the day part (#s_dt).
Each line is taking #s_dt, adding 0, 1, 2, 3 etc, casting as VARCHAR, adding '0' to the left (so that it is at least 2 chars in length) then taking the right two chars (the '0' and RIGHT operation just ensure anything under 10 have a leading '0').
It is possible to do this using dynamic SQL, however I would also consider looking at the pivot operators to see if they can achieve what you are after a lot more efficiently.
https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

How to Update a Column

I have SQL Express 2012 with a table that I added a column (integer) for a Word Count and the table already has a few hundred rows. I am not sure how I update the column to have the word count from the "entry" column.
I created a query that shows me the data, but how do I use this to update the table to store the Word Count for each entry?
SELECT
ID,
[UserName],
[DateCreated],
LEN([Entry]) - LEN(REPLACE([Entry], ' ', '')) + 1 AS 'Word Count'
FROM [dbo].[Notes]
The verb in the SQL language to update data in a table is not surprisingly UPDATE. The documentation has the full syntax.
If you want to update all rows and there are no NULL values in the Entry column (that would make the calculation fail) then this query will update a column named WordCount:
UPDATE Notes SET WordCount = LEN([Entry]) - LEN(REPLACE([Entry], ' ', '')) + 1
Try this piece of code.
UPDATE Notes SET
WordCount = LEN([Entry]) - LEN(REPLACE([Entry], ' ', '')) + 1
This should then update all rows in the table with the word count for that row.
Thanks,
Here is how you could do this so that your values are always current. Two big advantages here. First, you don't have to ever update your table. Second, the values will ALWAYS be current even if somebody updates your table with a query and doesn't update the WordCount.
create table #test
(
Entry varchar(100)
, WordCount as LEN(Entry) - LEN(REPLACE(Entry, ' ', ''))
)
insert #test
select 'two words' union all
select 'three words now'
select * from #test
drop table #test

Need to remove data from a substring

I haven't the foggiest how to remove a substring from my column, I have been looking here for a few days and everyone seems to want to remove data from the end not the beginning.
Column data: /data/data/data.com --data=nameiwant2keep
Column name: column1
Table name: table1
Thank you for any help.
Assuming you wanted to keep just the nameiwant2keep part, and there won't be any other parameters in the column data, you can search for the index of the = sign and take the substring from the next character to the end of the string:
UPDATE
table1
SET
column1 = SUBSTRING(column1, CHARINDEX('=', column1, 0) + 1, LEN(column1))
Try this for proof:
DECLARE #column1 varchar(max)
SET #column1 = '/data/data/data.com --data=nameiwant2keep'
SELECT
SUBSTRING(#column1, CHARINDEX('=', #column1, 0) + 1, LEN(#column1))

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