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.
Related
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,' ','')
I am trying to create a sql server query select. I have one argument that can be null or not.
WHen the #value is null I would like to return all mycolumns with the null value. If value is not null I want to return mycolumns with that value.
How best to handle this, i tried:
SELECT name FROM mytable
WHERE coalesce( #value,mycolumn)=mycolumn
I got a feeling it lies in the handling of the null value. How can I resolve?
where myColumn = #value or
(myColumn is null and #value is null)
SELECT T.name
FROM dbo.mytable T
WHERE
EXISTS (
SELECT #value INTERSECT SELECT T.mycolumn
)
;
1st case. when u pass a city name..
DECLARE #SearchType varchar(80);
SET #SearchType = 'Alamo';
Select * From Homes
where City = #SearchType OR Coalesce(#SearchType,'') = ''
2nd case. City null or empty.
SET #SearchType = '';
in first case you will get the result by city name. and in 2nd case you will get all the results.
Try:
SELECT name FROM mytable where myColumn = #value or #value is null
Facing problem for generating SQL Server Query
In the Following query dynamic conditions are added to check whether value is null or not
Select *
From tblEmployees
where EmployeeName = Case
When #EmployeeName Is Not Null
Then #EmployeeName
Else EmployeeName
End
But I need to add IN () Conditions and the parameter with in the IN () could be null or blank also ,if the parameter /string which is passed to the IN condition is blank then i donot want to add that condition in the query.
So how can i Achieve this.A helping hand will be very useful for me.
Thanks and Regards,
D.Mahesh
Depending on value of your parameter (blank of not), you can create SQL string accordingly.
DECLARE #sqlCommand VARCHAR(1000)
IF(ISNULL(#YourParameter,'')='')
#sqlCommand = 'your query goes here'
ELSE
#sqlCommand = 'your query goes here'
and then, run it using dynamic query execution
EXEC (#sqlCommand)
If not dynamic query then,
SELECT ....
FROM ....
WHERE CASE WHEN ISNULL(#YourParameter,'')='' THEN '' ELSE EmployeeName END IN (ISNULL(#YourParameter,''))
See if this works...
I think the Dynamic query is the best solution, however you could put the "IS NULL" and "IS BLANK" condition in OR with your IN clause.
Something like that
Select *
From tblEmployees
where #EmployeeName is null or EmployeeName in (#EmployeeName)
When #EmployeeName is null, your IN clause will be ignored
If i get this right you have #EmployeeName = 'Name1,Name2,Name3' and you want to get the employees that is named Name1 or Name2 or Name3, also the variable #EmployeeName can be null or contain an empty string.
Instead of using IN you can split the string #EmployeeName on , and store it in a table variable or temporary table. Then you can use that table in a join against tblEmployees to get the rows you need.
There are a lot of posts in S.O. about how to split a string. Here is one recent variant.
Group by sql query on comma joined column
This will work for SQL Server 2005 or later.
declare #EmployeeName varchar(100) = 'Name2,Name3,Name5'
-- Null or empty will have a comma
set #EmployeeName = coalesce(#EmployeeName, '') + ','
-- cteNames splits the string to rows
;with cteNames
as
(
select
left(#EmployeeName, charindex(',', #EmployeeName)-1) as Name,
right(#EmployeeName, len(#EmployeeName)-charindex(',', #EmployeeName)) as EmployeeName
union all
select
left(EmployeeName, charindex(',', EmployeeName)-1) as Name,
right(EmployeeName, len(EmployeeName)-charindex(',', EmployeeName)) as EmployeeName
from cteNames
where charindex(',', EmployeeName) > 1
)
select E.*
from tblEmployees as E
inner join cteNames as N
on E.Name = N.Name or
#EmployeeName = ','
-- #EmployeeName = ',' will give you all names when #EmployeeName is null of empty
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.
I am using SQL Server 2005. I have a table with a text column and I have many rows in the table where the value of this column is not null, but it is empty. Trying to compare against '' yields this response:
The data types text and varchar are incompatible in the not equal to operator.
Is there a special function to determine whether the value of a text column is not null but empty?
where datalength(mytextfield)=0
ISNULL(
case textcolum1
WHEN '' THEN NULL
ELSE textcolum1
END
,textcolum2) textcolum1
Actually, you just have to use the LIKE operator.
SELECT * FROM mytable WHERE mytextfield LIKE ''
To get only empty values (and not null values):
SELECT * FROM myTable WHERE myColumn = ''
To get both null and empty values:
SELECT * FROM myTable WHERE myColumn IS NULL OR myColumn = ''
To get only null values:
SELECT * FROM myTable WHERE myColumn IS NULL
To get values other than null and empty:
SELECT * FROM myTable WHERE myColumn <> ''
And remember use LIKE phrases only when necessary because they will degrade performance compared to other types of searches.
SELECT * FROM TABLE
WHERE ISNULL(FIELD, '')=''
Use the IS NULL operator:
Select * from tb_Employee where ename is null
I know this post is ancient but, I found it useful.
It didn't resolve my issue of returning the record with a non empty text field so I thought I would add my solution.
This is the where clause that worked for me.
WHERE xyz LIKE CAST('% %' as text)
Use DATALENGTH method, for example:
SELECT length = DATALENGTH(myField)
FROM myTABLE
Instead of using isnull use a case, because of performance it is better the case.
case when campo is null then '' else campo end
In your issue you need to do this:
case when campo is null then '' else
case when len(campo) = 0 then '' else campo en
end
Code like this:
create table #tabla(
id int,
campo varchar(10)
)
insert into #tabla
values(1,null)
insert into #tabla
values(2,'')
insert into #tabla
values(3,null)
insert into #tabla
values(4,'dato4')
insert into #tabla
values(5,'dato5')
select id, case when campo is null then 'DATA NULL' else
case when len(campo) = 0 then 'DATA EMPTY' else campo end
end
from #tabla
drop table #tabla
I would test against SUBSTRING(textColumn, 0, 1)
Are null and an empty string equivalent? If they are, I would include logic in my application (or maybe a trigger if the app is "out-of-the-box"?) to force the field to be either null or '', but not the other. If you went with '', then you could set the column to NOT NULL as well. Just a data-cleanliness thing.
I wanted to have a predefined text("No Labs Available") to be displayed if the value was null or empty and my friend helped me with this:
StrengthInfo = CASE WHEN ((SELECT COUNT(UnitsOrdered) FROM [Data_Sub_orders].[dbo].[Snappy_Orders_Sub] WHERE IdPatient = #PatientId and IdDrugService = 226)> 0)
THEN cast((S.UnitsOrdered) as varchar(50))
ELSE 'No Labs Available'
END
You have to do both:
SELECT * FROM Table WHERE Text IS NULL or Text LIKE ''
I know there are plenty answers with alternatives to this problem, but I just would like to put together what I found as the best solution by #Eric Z Beard & #Tim Cooper with #Enrique Garcia & #Uli Köhler.
If needed to deal with the fact that space-only could be the same as empty in your use-case scenario, because the query below will return 1, not 0.
SELECT datalength(' ')
Therefore, I would go for something like:
SELECT datalength(RTRIM(LTRIM(ISNULL([TextColumn], ''))))
try this:
select * from mytable where convert(varchar, mycolumn) = ''
i hope help u!
DECLARE #temp as nvarchar(20)
SET #temp = NULL
--SET #temp = ''
--SET #temp = 'Test'
SELECT IIF(ISNULL(#temp,'')='','[Empty]',#temp)
It will do two things:
Null check and string null check
Replace empty value to default value eg NA.
SELECT coalesce(NULLIF(column_name,''),'NA') as 'desired_name') from table;