I am having an issue with concatenation. Here is the problem-
When My Date is NULL I want NULL to be retuned but when the date is not Null I want the Values to be enclosed by '. Example '08/21/2021 11:20:23'.
The code below is not showing the addition of '. What am I missing here?
var cmd = ` Select Case When max(DATE1) IS NULL then NULL else concat('''', Max(TO_VARCHAR(DATE1)),'''') end as Max_DT from Table1
where TABLE_NAME= ''${ITableName}'' ;`;
// Run the statement.
var sql = snowflake.createStatement({sqlText: cmd});
var result = sql.execute();
result.next();
When My Date is NULL I want NULL to be retuned but when the date is not Null I want the Values to be enclosed by '
The CASE expression seems to be superfluous, as TO_VARCHAR() could handle it itself TO_VARCHAR(MAX(DATE1), '''mm/dd/yyyy, hh24:mi:ss'''):
CREATE OR REPLACE TABLE Table1(TABLE_NAME TEXT,DATE1 DATETIME)
AS
SELECT * FROM (VALUES( 'a', CURRENT_DATE), ('b', NULL));
SELECT TABLE_NAME,
TO_VARCHAR(MAX(DATE1), '''mm/dd/yyyy, hh24:mi:ss'''),
TO_VARCHAR(MAX(DATE1), 'mm/dd/yyyy, hh24:mi:ss')
FROM Table1;
GROUP BY TABLE_NAME;
Output:
Related
I have a column which has varchars like "172.54". I am trying to insert into another table where this columns datatype is float. I am getting error saying can not convert datatype varchar to float. So I do
SELECT *
FROM TBL
WHERE ISNUMERIC(COLNAME) <> 1
And I get no results. But casting is not working. So I look and I have empty strings in that column. So I try to
SELECT *
FROM TBL
WHERE COLNAME = ''
And also every other different amount of spaces.
I ultimately just want to convert the empty strings to null
Also len(colname) = 1
declare #test varchar(10) = ' ' -- any number of spaces is equivalent to ''
select try_convert( float, #test ) as floatval -- '' gives you 0
select case when #test = '' then NULL else try_convert( float, #test ) end as floatval -- value '' returns NULL instead of 0
I guess you column has some characters other than numeric data. Also empty string will be converted to zero it will not throw error.
To filter Numeric data use
COLNAME not like '%[^0-9]%'
Try something like this
insert into tablename (col1,col2)
SELECT col1,col2 FROM TBL
COLNAME not like '%[^0-9]%'
When I attempt to import a .csv comma-delimited flat file into a Microsoft SQL server 2008R2 64-bit instance, for string columns a NULL in the original data becomes a literal string "NULL" and in a numeric column I receive an import error. Can anyone please help???
KISS
Pre-process it, Replace all "NULL" with "".
ie the .csv file will have
,,
Instead of
NULL,NULL,
Seems to do the job for me.
Put the data into a staging table and then insert to the production table using SQL code.
update table1
set field1 = NULL
where field1 = 'null'
Or if you want to do a lot of fields
update table1
set field1 = case when field1 = 'null' then Null else Field1 End
, field2 = case when field2 = 'null' then Null else Field2 End
, field3 = case when field3 = 'null' then Null else Field3 End
Adding to HLGEM's answer, I do it dynamically, I load into staging table here all column types are VARCHAR and then do:
DECLARE #sql VARCHAR(MAX) = '';
SELECT #sql = CONCAT(#sql, '
UPDATE [staging].[',[TABLE_NAME],']
SET [',[COLUMN_NAME],'] = NULL
WHERE [',[COLUMN_NAME],'] = ''NULL'';
')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE [TABLE_SCHEMA] = 'staging'
AND [TABLE_NAME] IN ('MyTableName');
SELECT #sql;
EXEC(#sql);
Then do:
INSERT INTO [dbo].[MyTableName] ([col1], [col2], [colN])
SELECT [col1], [col2], [colN]
FROM [staging].[MyTableName]
Where table [dbo].[MyTableName] is defined with the desired column types, this also fails and tells you in type conversion errors...
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
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;