Inserting into One Field Select statement Results - sql

I am using Oracle databases. I have an sql table PS_Z_STAGE_TEST_JE that has three fields (EMPLID, LAST_NAME, FIRST_NAME).
I am trying to do a select statement that will pull many EMPLIDs from sql table:ps_vc_plan_mem and insert them into the EMPLID column while leaving the other two fields (LAST_NAME and FIRST_NAME) null.
Below is my SQL but it will say
Cannot insert null Value into LAST_NAME
when I try to run it.
INSERT INTO sysadm.PS_Z_STAGE_TEST_JE (EMPLID)
SELECT DISTINCT(emplid)
FROM ps_vc_plan_mem
WHERE vc_plan_id IN ('PNC-RS','PNC-SO','PNC-ESPP');

The only obvious problem that I see with your query is the asterisk at the end:
INSERT INTO sysadm.PS_Z_STAGE_TEST_JE(EMPLID)
SELECT DISTINCT emplid
FROM ps_vc_plan_mem
WHERE vc_plan_id IN ('PNC-RS', 'PNC-SO', 'PNC-ESPP');
Note that distinct is not a function. It is a modifier on select, so the parentheses don't mean anything.

The error message is exactly what it says it is. Your last_name column must be defined as not null. Therefore, you can't insert a null into it. Since you didn't define what to insert into the column in your insert, it tries to insert null by default and fails.
You must insert something into last name. I would suggest either a default string or an empty string if you can't get an actual last name to insert.
INSERT INTO sysadm.PS_Z_STAGE_TEST_JE (EMPLID, LAST_NAME)
SELECT DISTINCT(emplid), 'N/A'
FROM ps_vc_plan_mem
WHERE vc_plan_id IN ('PNC-RS','PNC-SO','PNC-ESPP');
Alternatively, you could alter your table so that last_name is nullable.

There is a asterisk at the end of your SQL statement. Please remove and retry.
If [sysadm].[PS_Z_STAGE_TEST_JE] table has a PK, you might want truncate the table before running the statement.

Related

Insert row to database based on form values not currently in database

I am using Access 2013 and I am trying to insert rows to a table but I don't want any duplicates. Basically if not exists in table enter the data to table. I have tried to using 'Not Exists' and 'Not in' and currently it still does not insert to table. Here is my code if I remove the where condition then it inserts to table but If I enter same record it duplicates. Here is my code:
INSERT INTO [UB-04s] ( consumer_id, prov_id, total_charges, [non-covered_chrgs], patient_name )
VALUES ([Forms]![frmHospitalEOR]![client_ID], [Forms]![frmHospitalEOR]![ID], Forms![frmHospitalEOR].[frmItemizedStmtTotals].Form.[TOTAL BILLED], Forms![frmHospitalEOR].[frmItemizedStmtTotals].Form.[TOTAL BILLED], [Forms]![frmHospitalEOR]![patient_name])
WHERE [Forms]![frmHospitalEOR]![ID]
NOT IN (SELECT DISTINCT prov_id FROM [UB-04s]);
You cannot use WHERE in this kind of SQL:
INSERT INTO tablename (fieldname) VALUES ('value');
You can add a constraint to the database, like a unique index, then the insert will fail with an error message. It is possible to have multiple NULL values for several rows, the unique index makes sure that rows with values are unique.
To avoid these kind of error messages you can build a procedure or use code to check data first, and then perform some action - like do the insert or cancel.
This select could be used to check data:
SELECT COUNT(*) FROM [UB-04s] WHERE prov_id = [Forms]![frmHospitalEOR]![ID]
It will return number of rows with the spesific value, if it is 0 then you are redy to run the insert.

SQL Insert Query With Condition

I am trying to insert values into 1 column of a table when a condition is satisfied.
Note: The table already contains data for all the columns but for 1 which is empty. I would like to insert value into this 1 column depending on the WHERE clause.
I have this query:
INSERT INTO <TABLE_NAME>
(COLUMN_NAME)
(VALUE)
WHERE <CONDITION>
I am getting an exception:
Incorrect Syntax Near WHERE Keyword
I am able to do this using UPDATE:
UPDATE <TABLE_NAME>
SET <COL_NAME>
WHERE <CONDITION>
But was wondering why the INSERT query was failing. Any advise appreciated.
As I understand your problem, you already have data in one row, and one column in that row does not have value, so you want to add value in to that column.
This the scenario for Update existing row, not the insert new row. You have to use UPDATE clause when data already present and you want to modify record(s). Choose insert when You want to insert new row in table.
So in your current scenario, Update Clause is your friend with Where Clause as you want to modify subset of records not all.
UPDATE <TABLE_NAME>
SET <COL_NAME>
WHERE <CONDITION>
INSERT Clause does not have any Where Clause as per any RDBMS syntax(I think). Insert is condition less sql query, While SELECT, UPDATE, DELETE all are conditional commands, you can add Where Clause in all later ones.
In order to add a value into the one column when the rows are already populated, you will need to use the update statement.
If you need to insert a new row that has a where clause, you will need to use an insert into select statement:
INSERT INTO <table> (<columns>)
SELECT <columns>
FROM <table>
WHERE <condition>;
The SQL Insert dont accept where parameters, you could check this: SQL Insert Definition...
I do not know the whole question of what you want to do, but just using the INSERT statement is not possible, however it is possible to condition the insertion of data into a table, if this data is dependent on another table or comes from another table ... check here... SQL Insert explain in wikipedia
like this:
Copying rows from other tables
INSERT INTO phone_book2
SELECT *
FROM phone_book
WHERE name IN ('John Doe', 'Peter Doe')
or
INSERT INTO phone_book2 ( [name], [phoneNumber] )
SELECT [name], [phoneNumber]
FROM phone_book
WHERE name IN ('John Doe', 'Peter Doe')
Based on your question I have the feeling that you are trying to UPDATE a column in a table rather than insert.
Something like:
UPDATE column SET value WHERE different_column_value = some_value
I know this is kinda late, for those who still want to use the where clause in an insert query, it's kinda possible with a hack.
My understanding is that, you want to insert only if a condition is true. Let's assume you have a column in your database "surname" and you want to insert only if a surname doesn't exist from the table.
You kinda want something like INSERT INTO table_name blha blha blah WHERE surname!="this_surname".
The solution is to make that cell unique from your admin panel.
Insert statement will insert a new record. You cannot apply a where clause to the record that you are inserting.
The where clause can be used to update the row that you want.
update SET = where .
But insert will not have a where clause.
Hope this answers your question
INSERT syntax cannot have WHERE clause. The only time you will find INSERT has WHERE clause is when you are using INSERT INTO...SELECT statement.
I take it the code you included is simply a template to show how you structured your query. See the SO questions here, here and the MSDN question here.
In SQL Server (which uses Transact-SQL aka T-SQL) you need an UPDATE query for INSERT where columns already have values - by using the answer #HaveNoDisplayName gave :)
If you are executing INSERT / UPDATE from code (or if you need it regularly) I would strongly recommend using a stored procedure with parameters.
You could extend the procedure further by adding an INSERT block to the procedure using an IF-ELSE to determine whether to execute INSERT new record or UPDATE an existing, as seen in this SO answer.
Finally, take a look at SQLFiddle for a sandbox playground to test your SQL without risk to your RDMS :-)
Private case I found useful: Conditional insert which avoids duplications:
-- create a temporary table with desired values
SELECT 'Peter' FirstName, 'Pan' LastName
INTO #tmp
-- insert only if row doesn't exist
INSERT INTO Persons (FirstName, LastName)
SELECT *
FROM #tmp t
WHERE NOT EXISTS (SELECT * FROM Persons where FirstName=t.FirstName and LastName=t.LastName)
If the data need to be added for a column for an existing row then it’s UPDATE.
INSERT is creating a new row in the table.
For conditional INSERT, you can use the MERGE command.

How to insert multiple rows in the same table-Oracle 10g

I created a table in Oracle SQL :
create table t1
(
empno number(6) PRIMARY KEY,
empname varchar(30),
hiredate date,
basic number(8),
deptno number(4)
);
And now I am inserting values into the table using a single query:
insert into t1 values((131309,'HP','20-FEB-04',2000000,1235)
(131310,'HT','20-APR-14',120020,1234));
But this shows error:
insert into t1 values((131309,'HP','20-FEB-04',2000000,1235),
*
ERROR at line 1:
ORA-00907: missing right parenthesis
How do I correct this?
An INSERT VALUES statement always inserts exactly 1 row. If you want to insert multiple rows with hard-coded values, the most common approach would simply be to execute two separate INSERT statements.
insert into t1 values(131309,'HP','20-FEB-04',2000000,1235);
insert into t1 values(131310,'HT','20-APR-14',120020,1234);
If you really wanted to, you could select your hard-coded values from dual and then do an INSERT SELECT
insert into t1
select 131309, 'HP', '20-FEB-04',2000000,1235 from dual
union all
select 131310,'HT','20-APR-14',120020,1234 from dual
Or you could do an INSERT ALL
insert all
into t1 values(131309,'HP','20-FEB-04',2000000,1235)
into t1 values(131310,'HT','20-APR-14',120020,1234)
select * from dual
Personally, I'd just use two statements.
Although this isn't related to your question, a couple of comments
Always, always list out the columns in your insert statement. You'll make your SQL much more robust so that if you add new columns in the future that allow NULL values your statements will still work. And you'll avoid lots of bugs when the column list is right there rather than hoping that someone remembers the order of columns in the table.
If you're inserting a value into a date column, use a date not a string literal that represents a date. Relying on implicit data type conversion is a source of many bugs. Use an explicit to_date or use ANSI date literals. And use 4-digit years.

Multiple returend values of SQL sub-query

I am using PostgreSQL 9.1, I wrote the following SQL statement:
INSERT INTO "Tracking" VALUES
((SELECT "studentID" FROM "Student" WHERE "studentClass"='2'),false,4,false);
The issue is that the sub-query :
SELECT "studentID" FROM "Student" WHERE "studentClass"='2'
returned more than one value, and it is supposed to do that(I want to execute the main query per each returned value of sub-query), but by this way the Query will not be executed. Any Idea?
Try this:
INSERT INTO "Tracking"
SELECT "studentID",false,4,false
FROM "Student" WHERE "studentClass"='2'
Then use INSERT INTO... SELECT statement
INSERT INTO "Tracking"
SELECT "studentID" , false , 4 , false
FROM "Student"
WHERE "studentClass" = '2'
One thing to make sure about this statement is to make sure that table Tracking contains only 4 column or else you will getting number of columns mismatched with the supplied value. If for instance you have more than 4 columns, define the column name on the INSERT clause on which you want to save those values.

iSeries DB2 - Is there any way to select the identity value from an insert statement?

I know we're rare, us poor folk that are using iSeries for DB2/AS400, but I'm hoping someone can answer this simple question. Is there any way to return the identity value from an insert statement without using two lines of SQL? I'm being forced to use inline SQL in C# to perform an insert, and then I need to use the identity generated for the insert for something later on. Simply put, I need the iSeries DB2 equivalent of Oracle's "RETURNING." I.e.,
INSERT INTO AwesomeTable (column1, column2, etc.)
VALUES (value1, value2, etc.)
RETURNING something;
Anyone? Thanks in advance.
EDIT: Unless someone knows of a way I can execute two lines of SQL in one IBM.Data.DB2.iSeries.iDB2Command (not a stored proc), I would like to do this all in one line of SQL
I am not sure of iSeries, but the following worked on db2v8.1:
Consider 'ID' is the name of your identity column. The following stmt will return the newly generated id (the same one that gets inserted by the insert stmt):
SELECT ID FROM FINAL TABLE (
INSERT INTO AwesomeTable (column1, column2, etc.)
VALUES (value1, value2, etc.)
)
Some explanation I found on the publib site: (I used it for reference to test my query above)
/* The following SELECT statement references an INSERT statement in its
FROM clause. It inserts an employee record from host variables into
table company_b. The current employee ID from the cursor is selected
into the host variable new_id. The keywords FROM FINAL TABLE
determine that the value in new_id is the value of ID after the
INSERT statement is complete.
Note that the ID column in table company_b is generated and without
the SELECT statement an additional query would have to be made in
order to retreive the employee's ID number.
*/
EXEC SQL SELECT ID INTO :new_id
FROM FINAL TABLE(INSERT INTO company_b
VALUES(default, :name, :department, :job, :years, :salary,
:benefits, :id));
Hope this helps :)
You need to use the IDENTITY_VAL_LOCAL scalar function. From the IBM documentation:
IDENTITY_VAL_LOCAL is a
non-deterministic function that
returns the most recently assigned
value for an identity column.
Example:
CREATE TABLE EMPLOYEE
(EMPNO INTEGER GENERATED ALWAYS AS IDENTITY,
NAME CHAR(30),
SALARY DECIMAL(5,2),
DEPT SMALLINT)
INSERT INTO EMPLOYEE
(NAME, SALARY, DEPTNO)
VALUES('Rupert', 989.99, 50)
SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1
Here's an example :
CREATE TABLE AUTOINC (
AUTO91 INTEGER GENERATED ALWAYS AS IDENTITY,
SCDS91 CHAR(35) NOT NULL DEFAULT '',
MCLD91 DECIMAL(3,0) NOT NULL DEFAULT 0,
CONSTRAINT PK_AUTOINC PRIMARY KEY(AUTO91));
// Notice the default keyword where the auto increment field is.
insert into AUTOINC Values( default ,'SYSC' , 0 )
// And using the function to return the last identity column value.
// Note: fetch first row only.
select **IDENTITY_VAL_LOCAL**() from AUTOINC **fetch first row only**