Insert Data into SQL Table with primary key column - r

I have a table in a SQL Server database and an R script that appends data to that tabl.
The db table contains a primary key ("ID"), which is just a scope_identity field
When I try to append the table into that location, I keep running into the following error
> sqlSave(Conn[["DbCon"]],
+ dat = OutputDataFinal,
+ tablename = "DataSci_StandardTransferPriority",
+ verbose = TRUE,
+ append = TRUE,
+ rownames = FALSE)
Query:
INSERT INTO "DataSci_StandardTransferPriority" (
"ID", "LeadSourceName", "AgeCategory", "ZipColor", "LeadCount_Sum",
"OB_TotalDials_Sum", "ContactRate", "TransferRate", "HypTransfers", "LaborCPT",
"MarketingCpt", "CloseRate", "PDLTR", "Policy_Count_Sum", "InboundDials_Sum",
"LeadCost_Sum", "PPT", "PPH", "ContactRateXCloseRate", "ContactRateXCloseRateTarget",
"ModelValue", "SourcePriority", "InsertTS"
)
VALUES ( ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? )
Error in odbcUpdate(channel, query, mydata, coldata[m, ], test = test, :
missing columns in 'data'
How can I append and ignore the issue with the primary key?

In standard INSERT operation dont specify identity column. It automatically provides next incremental identity value. For example:
CREATE TABLE #TempTable (
[ID] [bigint] NOT NULL IDENTITY(1, 1) PRIMARY KEY,
[Column1] [varchar](50) NULL,
[Column2] [decimal](19, 3) NOT NULL
);
INSERT INTO #TempTable (
[Column1],
[Column2]
)
VALUES
('first insert', 50.2),
('second insert', 84.2);
SELECT *
FROM #TempTable
DROP TABLE #TempTable;
The result was:
ID
Column1
Column2
1
first insert
50.200
2
second insert
84.200
If you want insert on identity column any way - enable IDENTITY_INSERT. But be care for data integrity issues.
CREATE TABLE #TempTable (
[ID] [bigint] NOT NULL IDENTITY(1, 1) PRIMARY KEY,
[Column1] [varchar](50) NULL,
[Column2] [decimal](19, 3) NOT NULL
);
INSERT INTO #TempTable (
[Column1],
[Column2]
)
VALUES ('first insert', 50.2);
SET IDENTITY_INSERT #TempTable ON;
INSERT INTO #TempTable (
[ID],
[Column1],
[Column2]
)
VALUES
(4, 'second insert', 84.63),
(2, 'third insert', 99.56);
SET IDENTITY_INSERT #TempTable OFF;
INSERT INTO #TempTable (
[Column1],
[Column2]
)
VALUES ('four insert', 100.32);
SELECT *
FROM #TempTable
DROP TABLE #TempTable;
And the result:
ID
Column1
Column2
1
first insert
50.200
2
third insert
99.560
4
second insert
84.630
5
four insert
100.320

Related

Create index if not exist

ALL,
SQL> SELECT 1 FROM all_indexes WHERE table_name = UPPER( 'abcatcol' ) AND index_name = UPPER( 'abcatcol_tnam_ownr_cnam' );
no rows selected
SQL> CREATE INDEX abcatcol_tnam_ownr_cnam ON abcatcol(abc_tnam, abc_ownr, abc_cnam);
CREATE INDEX abcatcol_tnam_ownr_cnam ON abcatcol(abc_tnam, abc_ownr, abc_cnam)
*
ERROR at line 1:
ORA-01408: such column list already indexed
SQL> SELECT 1 FROM all_indexes WHERE table_name = UPPER( 'abcatcol' );
1
----------
1
SQL> SELECT index_name FROM all_indexes WHERE table_name = UPPER( 'abcatcol' );
INDEX_NAME
------------------------------
SYS_C007087
SQL >
What am I missing? Why can't I create an index?
EDIT:
SQL> select index_name, listagg(column_name, ', ') within group(order by 1)-- over(partition by index_name)
2 from dba_ind_columns
3 where table_name = 'ABCATCOL'
4 group by index_name;
INDEX_NAME
------------------------------
LISTAGG(COLUMN_NAME,',')WITHINGROUP(ORDERBY1)--OVER(PARTITIONBYINDEX_NAME)
--------------------------------------------------------------------------------
SYS_C007087
ABC_CNAM, ABC_OWNR, ABC_TNAM
SQL> SELECT index_name FROM all_indexes WHERE table_name = UPPER( 'abcatcol' );
INDEX_NAME
------------------------------
SYS_C007087
SQL>
EDIT2:
The suggested question utilizes PL/SQL. I want to understand how to do that using standard SQL and why my queries do not work as expected.
EDIT3:
This is the table definition:
CREATE TABLE abcatcol(abc_tnam char(129) NOT NULL, abc_tid integer, abc_ownr char(129) NOT NULL, abc_cnam char(129) NOT NULL, abc_cid smallint, abc_labl char(254), abc_lpos smallint, abc_hdr char(254), abc_hpos smallint, abc_itfy smallint, abc_mask char(31), abc_case smallint, abc_hght smallint, abc_wdth smallint, abc_ptrn char(31), abc_bmap char(1), abc_init char(254), abc_cmnt char(254), abc_edit char(31), abc_tag char(254), PRIMARY KEY( abc_tnam, abc_ownr, abc_cnam ));
So I guess since those fields are part of the PK Otacle already made the index, right?
You are looking for an index by it's name whereas oracle says to you this set of columns has been already indexed.
It means there is already an index with another name over that column set.
You need to check against dba_ind_columns table to get the index name over that column set
UPD. Here is the query to help you out to find the columns indexed
select index_name, listagg(column_name, ', ') within group(order by 1)-- over(partition by index_name)
from dba_ind_columns
where table_name = 'TABLE_NAME'
group by index_name;

Getting error :Error(2,3): PL/SQL: SQL Statement ignored Error(8,5): PL/SQL: ORA-00984: column not allowed here

My code is like below.
create table XXINF_DB_OBJECT_DDL_LOG (
EVENT_DATE DATE NOT NULL,
EVENT_TIMESTAMP TIMESTAMP NOT NULL,
EVENT_TYPE VARCHAR2(30) NOT NULL,
OBJECT_TYPE VARCHAR2(30) NOT NULL,
OBJECT_OWNER VARCHAR2(30) NOT NULL,
OBJECT_NAME VARCHAR2(30) NOT NULL,
DB_USER VARCHAR2(30) NOT NULL,
OS_USER VARCHAR2(100) ,
HOST_NAME VARCHAR2(100),
HOST_IP_ADDRESS VARCHAR2(30)
);
create or replace trigger XXINF_DB_OBJECT_DDL_LOG_AUDIT
AFTER DDL ON schema
begin
insert into XXINF_DB_OBJECT_DDL_LOG values(
sysdate,
systimestamp,
ora_sysevent,
ora_dict_obj_type,
ora_dict_obj_owner,
ora_dict_odj_name,
ora_login_user,
SYS_CONTEXT('USERENV','OS_USER'),
SYS_CONTEXT('USERENV','TERMINAL'),
SYS_CONTEXT('USERENV','IP_ADDRESS')
);
END;
/
when I execute get error:
Error(2,3): PL/SQL: SQL Statement ignored Error(8,5): PL/SQL:
ORA-00984: column not allowed here
Please use the corrections as below:
create or replace trigger XXINF_DB_OBJECT_DDL_LOG_AUDIT
AFTER DDL ON SCHEMA
begin
insert into XXINF_DB_OBJECT_DDL_LOG
(
EVENT_DATE,
EVENT_TIMESTAMP,
EVENT_TYPE,
OBJECT_TYPE,
OBJECT_OWNER,
OBJECT_NAME,
DB_USER,
OS_USER,
HOST_NAME,
HOST_IP_ADDRESS
)
values
(
sysdate,
systimestamp,
ora_sysevent,
ora_dict_obj_type ,
ora_dict_obj_owner,
ora_dict_obj_name ,
ora_login_user ,
SYS_CONTEXT('USERENV','OS_USER'),
SYS_CONTEXT('USERENV','TERMINAL'),
SYS_CONTEXT('USERENV','IP_ADDRESS') );
END;
/

sqlite3: how to select same row twice when there is a match?

Create SOF.SQL
CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US');
INSERT INTO "android_metadata" VALUES ('en_US');
CREATE TABLE main.t_def (
_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
word TEXT(20) not null,
word_def TEXT(20) not null
);
insert into t_def (word, word_def) values ('ball','spherical object');
insert into t_def (word, word_def) values ('cat','feline');
insert into t_def (word, word_def) values ('dog','common housekept');
CREATE TABLE main.t_a (
_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
corr_answer TEXT(20) not null,
user_answer TEXT(20) not null,
is_correct INTEGER not null
);
insert into t_a (user_answer, corr_answer, is_correct) values ('ball','cat',0);
insert into t_a (user_answer, corr_answer, is_correct) values ('dog','dog',1);
.exit
Then run:
sqlite3 foo.db < SOF.SQL
I want a result set that is:
ball|spherical object|cat|feline|0
This is the closest I have gotten:
select t_def.word, t_def.word_def from t_def, t_a where t_a.is_correct=0 and t_a.corr_answer=t_def.word;
To get values from two rows, you need two instances of the table:
SELECT t_a.user_answer,
user_def.word_def AS user_word_def,
t_a.corr_answer,
corr_def.word_def AS corr_word_def,
t_a.is_correct
FROM t_a
JOIN t_def AS user_def ON t_a.user_answer = user_def.word
JOIN t_def AS corr_def ON t_a.corr_answer = corr_def.word
WHERE NOT t_a.is_correct

Select Record with Repeated Status using Sql Query

i have one Schedule Table like
i want to look like select query data is:
1 and 11 is Duplicate trainer and Duplicate day,time
10 and 12 is Duplicate trainer, Duplicate vanueid and Duplicate date,time
so last two column are display is not Duplicate than available and is Duplicate than display notavailable
Here is the solution that is coming to my mind.There may some syntax issue but i given the logic which may help you.
DECLARE #duplicate TABLE (
trainerId INT,
dt varchar(50)
)
INSERT INTO #duplicate SELECT TrainerId , [Date] from tbl GROUP BY TrainerId , Date HAVING (COUNT(*) > 1)
SELECT * FROM #duplicate
DECLARE #tempTable TABLE (
trainerId INT,
dt varchar(50),
status int
)
INSERT INTO #tempTable
SELECT trainerId , [Date] , STATUS = (SELECT COUNT(*) FROM #duplicate where trainerId = tbl.TrainerId and dt = tbl.Date) FROM tbl
![enter image description here][2]SELECT * , CASE [status] WHEN 0 THEN 'Available' ELSE 'Not Available' END FROM #tempTable

Copy a subset of column data from one table to another

I have two tables with identical schema. Let's name them TestTable and TestTableTemp. I need to copy just two columns from TestTableTemp to TestTable without disrupting other data. The rows in TestTable are a subset of those in TestTableTemp. Let's say the columns that I need to copy are named Column1 and Column2 and that they have identical primary keys reference by column primaryKey.
In mysql I believe this could be done as such or something similar:
UPDATE TestTable, TestTableTemp
SET TestTable.Column1 = TestTableTemp.Column1, TestTable.Column2 = TestTableTemp.Column2
WHERE TestTable.primaryKey = TestTableTemp.primaryKey
Sqlite does not allow for multiple tables to be defined on the update statement as can been seen in their reference data here: http://www.sqlite.org/lang_update.html
The best I could come up with is such:
UPDATE TestTable SET
Column1 = (select TestTableTemp.Column1 from TestTableTemp, TestTable where TestTable.primaryKey = TestTableTemp.primaryKey),
Column2 = (select TestTableTemp.Column2 from TestTableTemp, TestTable where TestTable.primaryKey = TestTableTemp.primaryKey)
WHERE EXISTS(select * from TestTableTemp where TestTable.primaryKey = TestTableTemp.primaryKey"
This gives me a syntax error near "." I am guessing this is because I cannot reference TestTable in the scalar expressions.
Can anyone point me in the right direction? Any help is much appreciated.
EDIT:
I cleaned up the second query a bit. It seems to just set the Column1 and Column2 to the first row from that column from TestTableTemp.
Your original query for comparison:
UPDATE TestTable, TestTableTemp
SET TestTable.Column1 = TestTableTemp.Column1
, TestTable.Column2 = TestTableTemp.Column2
WHERE TestTable.primaryKey = TestTableTemp.primaryKey
Here is the working query (I just slightly changed your version):
http://sqlfiddle.com/#!5/f3a19/9
UPDATE TestTable
SET
Column1 = ( SELECT TestTableTemp.Column1
FROM TestTableTemp
WHERE TestTableTemp.primaryKey = TestTable.primaryKey )
,Column2 = ( SELECT TestTableTemp.Column2
FROM TestTableTemp
WHERE TestTableTemp.primaryKey = TestTable.primaryKey )
WHERE EXISTS( SELECT NULL
FROM TestTableTemp
WHERE TestTableTemp.primaryKey = TestTable.primaryKey )
;

Resources