bigint(20) within sql query in R - r

In my SQl base the type of the item_id is bigint(20)
I need to extract a list of item_id and then insert it into another table to make a join then.
But R converts item_id into the "double" in the result of the query.
{query.1<-c("Select ITEM_ID FROM DISPLAY WHERE client_key=121")
query.1 <- paste (query.1, collapse = " ")
items<- dbGetQuery(connect.base, query.1)
typeof(items$ITEM_ID)
[1] "double"}
So I can't input this values into the new table as the join will not work
there is no bigint(20) in R, so probably I need to convert to caracter, but how can i do it within RMySQL query?
Any help will be much appriciate

You have to create a table in mysql with specified fields. Like
dbSendQuery(connect.base, "create table new_table(
ITEM_ID bigint not null,
key(ITEM_ID))ENGINE=InnoDB DEFAULT CHARSET=utf8;")
Then if you write a DB table with R using append=TRUE the value will be in the right format:
dbWriteTable(connect.base, "new_table",items, append=TRUE,row.names=F)

Related

How to create a Teradata table by copying and modifying another Table?

I am trying to create a new Teradata table by copying another table, but also need to add one new column, based on a condition of another column from the old table while copying, can you help me on the code?
create Table new_table as
(select *
from old_table) with data
ALTER TABLE new_table ADD new_col varchar(20) check(new_col in ('National', 'Local')
-- there is a column in the old_table with value ( 'Y', 'N'), how can i create the new column in the new_table with this condition: if Y new_col=national, if N, new_col=local?
Thank you.
You can't create a check constraint that will immediately be violated. Also note that CREATE TABLE AS (SELECT ...) results in all columns being nullable, and if you don't explicitly state a Primary Index the new table will use system default, e.g. first column alone as PI. A CASE expression can be used to populate the new column.
One possible sequence:
create Table new_table as old_table with no data; -- copy index definitions, NOT NULL attributes
ALTER TABLE new_table ADD new_col varchar(20) check(new_col in ('National', 'Local'));
INSERT new_table SELECT o.*,
CASE WHEN o.old_col = 'Y' THEN 'National' ELSE 'Local' END
FROM old_table o;

FIREDAC-UTF8 encoding is not supported when reading FTS table

When in DELPHI XE3 with Firedac we create a table table0 and insert text in UTF8 encoding all is OK.
CREATE TABLE table0 (mytext Ntext,publishdate date);
INSERT INTO table0 (mytext,publishdate) VALUES ('привет','1998-12-07');
But, when we create a FTS table and insert text in UTF8.
CREATE VIRTUAL TABLE table1 USING FTS4(mytext,publishdate);
INSERT INTO table1 (mytext,publishdate) VALUES ('привет','1998-12-07');
and read the data with
SELECT mytext FROM table1
we get "??????".
The same commands in SQLITE Expert Personal return "привет". It means that in the table after Insert command we have 'привет' and select returns the data not in UTF8 encoding.
What may be done to get from the table correct value with Firedac
ADQuery.Open('SELECT mytext FROM table1')?
I think it is FireDac bug.
I've changed the following lines in ADSQLiteTypeName2ADDataType procedure of uADPhysSQLite.pas unit
SetLen(AOptions.FormatOptions.MaxStringSize, False);
AType := dtAnsiString;
to
SetLen(AOptions.FormatOptions.MaxStringSize, True);
AType := dtWideString;
for the case ABaseTypeName = 'VARCHAR'
and
SELECT mytext FROM table0
returns the correct value at runtime. But at design time still we have '??????'.
But I don't think it's a good solution.
I believe you should directly set parameter type as AsWideString:
Query.SQL.Text:='INSERT INTO table1 (mytext, publishdate) VALUES (:mytext,: publishdate);';
Query.Params[0].AsWideString := mytext;
Query.Params[1].AsDate := publishdate;
Query.ExecSQL;
Reference: http://docwiki.embarcadero.com/RADStudio/Rio/en/Unicode_Support_(FireDAC)#Parameter_Values

Sybase iq cannot load table with datetime column

I'm trying to load table to a sybase iq database from a text file, and have a trouble loading datetime field... Always get error data type conversion is not possible. I tried a lot of ways in solving it...
creating varchar field and converting it to data
creating temp table and inserting values into my table from temp table using dateformat, cast, convert,
load table table_name(
datetime_column datetime('dd-mm-yyyy hh-mm-ss')
) from ...
Nothing helps. Any help? thanks.
So I found the solution
load table table_name (
temp_date ' | ',
-- dt datetime column
)
from file_name
---------------------------------------
set dateformat dmy;
update table_name set dt = temp_date
ALTER TABLE table_name
DROP temp_date

How to have an automatic timestamp in SQLite?

I have an SQLite database, version 3 and I am using C# to create an application that uses this database.
I want to use a timestamp field in a table for concurrency, but I notice that when I insert a new record, this field is not set, and is null.
For example, in MS SQL Server if I use a timestamp field it is updated by the database and I don't have to set it by myself. Is this possible in SQLite?
Just declare a default value for a field:
CREATE TABLE MyTable(
ID INTEGER PRIMARY KEY,
Name TEXT,
Other STUFF,
Timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);
However, if your INSERT command explicitly sets this field to NULL, it will be set to NULL.
You can create TIMESTAMP field in table on the SQLite, see this:
CREATE TABLE my_table (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name VARCHAR(64),
sqltime TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
);
INSERT INTO my_table(name, sqltime) VALUES('test1', '2010-05-28T15:36:56.200');
INSERT INTO my_table(name, sqltime) VALUES('test2', '2010-08-28T13:40:02.200');
INSERT INTO my_table(name) VALUES('test3');
This is the result:
SELECT * FROM my_table;
Reading datefunc a working example of automatic datetime completion would be:
sqlite> CREATE TABLE 'test' (
...> 'id' INTEGER PRIMARY KEY,
...> 'dt1' DATETIME NOT NULL DEFAULT (datetime(CURRENT_TIMESTAMP, 'localtime')),
...> 'dt2' DATETIME NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now', 'localtime')),
...> 'dt3' DATETIME NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%f', 'now', 'localtime'))
...> );
Let's insert some rows in a way that initiates automatic datetime completion:
sqlite> INSERT INTO 'test' ('id') VALUES (null);
sqlite> INSERT INTO 'test' ('id') VALUES (null);
The stored data clearly shows that the first two are the same but not the third function:
sqlite> SELECT * FROM 'test';
1|2017-09-26 09:10:08|2017-09-26 09:10:08|2017-09-26 09:10:08.053
2|2017-09-26 09:10:56|2017-09-26 09:10:56|2017-09-26 09:10:56.894
Pay attention that SQLite functions are surrounded in parenthesis!
How difficult was this to show it in one example?
Have fun!
you can use triggers. works very well
CREATE TABLE MyTable(
ID INTEGER PRIMARY KEY,
Name TEXT,
Other STUFF,
Timestamp DATETIME);
CREATE TRIGGER insert_Timestamp_Trigger
AFTER INSERT ON MyTable
BEGIN
UPDATE MyTable SET Timestamp =STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW') WHERE id = NEW.id;
END;
CREATE TRIGGER update_Timestamp_Trigger
AFTER UPDATE On MyTable
BEGIN
UPDATE MyTable SET Timestamp = STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW') WHERE id = NEW.id;
END;
To complement answers above...
If you are using EF, adorn the property with Data Annotation [Timestamp], then
go to the overrided OnModelCreating, inside your context class, and add this Fluent API code:
modelBuilder.Entity<YourEntity>()
.Property(b => b.Timestamp)
.ValueGeneratedOnAddOrUpdate()
.IsConcurrencyToken()
.ForSqliteHasDefaultValueSql("CURRENT_TIMESTAMP");
It will make a default value to every data that will be insert into this table.
you can use the custom datetime by using...
create table noteTable3
(created_at DATETIME DEFAULT (STRFTIME('%d-%m-%Y %H:%M', 'NOW','localtime')),
title text not null, myNotes text not null);
use 'NOW','localtime' to get the current system date else it will show some past or other time in your Database after insertion time in your db.
Thanks You...
If you use the SQLite DB-Browser you can change the default value in this way:
Choose database structure
select the table
modify table
in your column put under 'default value' the value: =(datetime('now','localtime'))
I recommend to make an update of your database before, because a wrong format in the value can lead to problems in the SQLLite Browser.

Add not null DateTime column to SQLite without default value?

I can't add a not null constraint or remove a default constraint. I would like to add a datetime column to a table and have all the values set to anything (perhaps 1970 or year 2000) but it seems like i cant use not null without a default and I cant remove a default once added in. So how can i add this column? (once again just a plain datetime not null)
Instead of using ALTER TABLE ADD COLUMN, create a new table that has the extra column, and copy your old data. This will free you from the restrictions of ALTER TABLE and let you have a NOT NULL constraint without a default value.
ALTER TABLE YourTable RENAME TO OldTable;
CREATE TABLE YourTable (/* old cols */, NewColumn DATETIME NOT NULL);
INSERT INTO YourTable SELECT *, '2000-01-01 00:00:00' FROM OldTable;
DROP TABLE OldTable;
Edit: The official SQLite documentation for ALTER TABLE now warns against the above procedure because it “might corrupt references to that table in triggers, views, and foreign key constraints.” The safe alternative is to use a temporary name for the new table, like this:
CREATE TABLE NewTable (/* old cols */, NewColumn DATETIME NOT NULL);
INSERT INTO NewTable SELECT *, '2000-01-01 00:00:00' FROM YourTable;
DROP TABLE YourTable;
ALTER TABLE NewTable RENAME TO YourTable;

Resources