Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting text to int in sqlite when querying

Tags:

c#

sqlite

I want to convert both of the following columns to integer (they were placed as text in the SQlite db) as soon as I select them.

 string sql4 = "select seq, maxLen from abc where maxLen > 30";

I think it might be done like this..(using cast)

 string sql4 = "select cast( seq as int, maxLen as int) from abc where maxLen > 30";

Not sure if it's right as I seem to be getting a syntax error.

How would I also convert the text to double

like image 505
Newuser Avatar asked Nov 18 '13 20:11

Newuser


People also ask

How do I convert a text to number in SQL?

TO_NUMBER converts a string to a number of data type NUMERIC. TO_CHAR performs the reverse operation; it converts a number to a string. CAST and CONVERT can be used to convert a string to a number of any data type. For example, you can convert a string to a number of data type INTEGER.

What is the difference between INTEGER and numeric in SQLite?

There is no difference between a NUMERIC value which is an integer and an INTEGER value which is an INTEGER -- they are both INTEGER and behave exactly the same.

What is difference between text and varchar in SQLite?

Some Differences Between VARCHAR and TEXT The VAR in VARCHAR means that you can set the max size to anything between 1 and 65,535. TEXT fields have a fixed max size of 65,535 characters. A VARCHAR can be part of an index whereas a TEXT field requires you to specify a prefix length, which can be part of an index.

Is SQLite case insensitive?

For one thing, databases vary considerably in how they handle text; for example, while some databases are case-sensitive by default (e.g. Sqlite, PostgreSQL), others are case-insensitive (SQL Server, MySQL).


2 Answers

You need to cast in where clause, not where you are selecting it.

string sql4 = "select seq, maxLen from abc where CAST(maxLen as INTEGER) > 30";

Also in your current cast version it will not work since CAST works for a single field.

For your question:

How would I also convert the text to double

cast it to REAL like:

CAST(maxLen as REAL)
like image 167
Habib Avatar answered Oct 19 '22 04:10

Habib


Syntax issue is you're putting two casts in one cast clause. Try this:

string sql4 = "select cast(seq as int), cast(maxLen as int) 
               from abc where maxLen > 30"

Like Habib pointed out, you should typecast the where clause, otherwise the comparison isn't numeric but textual.

string sql4 = "select cast(seq as int), cast(maxLen as int) 
               from abc where cast(maxLen as int) > 30"

And also, casting to float is simple use float instead of int (or you can use REAL which is same datatype in SQLite)

cast(maxLen as float)
like image 31
swdev Avatar answered Oct 19 '22 04:10

swdev