How do I write the SQL INSERT command in PHP - sql

How do I write the SQL INSERT command to add the data in the screenshot provided when I have already created a table?
CREATE TABLE Term (Term_Name VARCHAR(25), Term_StartDate DATE, TermEndDate DATE);
Term Table
I've attempted to type in the code, and this is the error that I get; screenshot attached.
Attempt at INSERT

You're very close! You don't want the SELECT to be bundled with the INSERTs.
You simply want the DML (Data Manipulation Language) statements to INSERT the data into the data. So, just use the INSERTS.
Then, use a SELECT statement to obtain the data that you want.
Here is a modified sample of what you did using SQL Fiddle.

Related

How to make a new copy of table without CREATE TABLE but using INSERT

I'm using SQL Server 2014 and trying to figure out some not trivia task.
I have a table PROPERTY and need to copy some of the data to absolutely new table PROPERTY_1 (PROPERTY_1 is not created and I'm not allowed to use CREATE TABLE). I have to use INSERT only!
I've googled some fancy commands like INSERT INTO from MySQL:
INSERT INTO PROPERTY_1 SELECT * FROM PROPERTY
but it's no help because (surprise-surprise!) PROPERTY_1 is not created.
Is it any possible way to pass this task or it's just some kind of weird task?
You must use Select Into as described in the Microsoft: documentation
You can use Select into to create the structure only and use Insert into to copy the data like below:
SELECT * INTO PROPERTY_1 FROM PROPERTY WHERE 1=0
INSERT INTO PROPERTY_1 SELECT * FROM PROPERTY
Benefits of using Select into to create the structure of the copy table:
You don't need to worry about the columns and their data types in the new table (PROPERTY_1) as those will be similar to the base table (PROPERTY). The new table schema will match the original schema, including identity columns.
There won't be any errors while inserting the records in the new table.

Inserting to one table, insert the ID to second table

Is it possible to populate a second table when I insert into the first table?
Insert post to table1 -> table 2 column recieves table1 post's unique id.
What I got so far, am I on the right track?
CONSTRAINT [FK_dbo.Statistics_dbo.News_News_NewsID] FOREIGN KEY ([News_NewsID]) REFERENCES [dbo].[News] ([NewsID])
Lots of ways:
an insert trigger
read SCOPE_IDENTITY() after the first insert, and use it to do a second
use the output clause to do an insert
Examples:
1:
create trigger Foo_Insert on Foo after insert
as
begin
set nocount on
insert Bar(fooid)
select id from inserted
end
go
insert Foo (Name)
values ('abc');
2:
insert Foo (Name)
values ('abc');
declare #id int = SCOPE_IDENTITY();
insert Bar(fooid)
select #id
3:
insert Bar(fooid)
select id from (
insert Foo (Name)
output inserted.id
values ('abc')) x
The only thing I can think of is that you can use a trigger to accomplish this. There is nothing "built in" to SQL Server that would do it. Why not just do it from your .NET code?
Yes it is, it sounds like you want a SQL Trigger, this would allow you to trigger logic based on actions on one table, to perform other actions in the DB. Here's another article on creating Simple SQL Triggers
SQL Server 2008 - Help writing simple INSERT Trigger
A Word of caution, this will do all the logic of updating the new table, outside of any C# code you write, it might sound nice to not have to manage it upfront, but you also lose control over when and if it happens.
So if you need to do something different later, now you have to update your regular code, as well as the trigger code. This type of logic can definitely grow, in large systems, and become a nightmare to maintain. Consider this, the alternative would be to build a method that adds the id to the new table after it inserts into the first table.
While i don't know what you're using to do your inserts assuming it's a SQL Command you can get back the ID on an identity column from the insert using Scope_Identity, found here
How to insert a record and return the newly created ID using a single SqlCommand?
if it's EF or some other ORM tool, they should either automatically update the entity, or have other mechanisms to deliver this data.

How do you copy Sql table from one database to another database with differ field names

I have a database name "EmpOld" with a table name "Employee" and a database name "EmpNew" with a table name "Employee".
The table structures are identical on both database tables except for the names in the table.
Here is a definition of the tables:
Database "EmpOld" table name "Employee" has following field names:
int e_id
char(20) e_fname
char(25) e_lname
Database "EmpNew" table "Employee" has following field names:
int id
char(20) fname
char(25) lname
Notice, the only difference in the tables is the "e_" prefix for field names are removed from the EmpNew Employee table.
How do I move data from EmpOld database to EmpNew database?
Is there a code that maps these field respectively.
Thanks community,
Nick
Well, you could just name them manually:
INSERT dbo.EmpNew(fname, lname) SELECT e_fname, e_lname FROM dbo.EmpOld;
If you want to do this without manually typing out the column names, there is magic in SSMS - just drag the Columns folder from each table into the appropriate spot in your query window (and then manually remove identity columns, timestamp, computed columns etc. if relevant).
There is no automatic way of mapping fields, unless with some code.
This can be done in two ways:
Using the SQL Import & Export Wizard
This is the most easy way to do this and here is an article that gives step by step to do this. The key is to change the mapping between the source and destination fields while importing the data.
Writing an SQL
This method requires both the databases to be accessible. Using a simple insert statement as follows this can be achieved
insert into EmpNew.dbo.Employee(id, fname, lname)
select
e_id, e_fname, e_lname
from
EmpOld.dbo.Employee
If they are on same sql server then the above will work good as is. If they are different sql server you may have to add a link server connection and prefix the table commands with that.
Is there a code that maps these field respectively.
No - you'll need to provide the mapping. If you're using an ETL tool like SSIS there may be a way to programatically map columns based on some criteria, but nothing built into SQL.
Maybe you can generate code with help from the tables sys.columns and other system tables so that you can make the copy-process run automatically.
I think you can't use:
insert into (...) (...)
because you have two databases. So just generate insert statements like:
insert into table (...) VALUES (...)
Please correct me if i misunderstood the question.
There are 2 ways you can do without the data loss.
1) you can use Insert statement
`
Insert into EmpNew (ID,fname,lname)
Select e_id, e_fname, e_lastname
from EmpOld
`
2) You can simple use Import-Export Wizard
Go to Start Menu > SQL Server 2008/2008R2/2012 > ImportandExport>
This will take you the wizard box
Select Source :- DataSource(ServerName) and Database where you are
extracting data from
Select Destination : DataSource(ServerName) and Database where you are extracting data to
Map the table
BE AWARE of PK/FK/Identity
you are good to go

SQL insert into 2 tables in one query

I have the following query in SQLRPGLE for DB2:
INSERT INTO ITEMS2 (PROGRAM, VLDFILE, VLDFLD,
SELFILE, SELFLD) VALUES(:SCAPP , 'CSTMR', 'CYC',
'BYC', 'BYCC');
I would like this query to be run in 2 libraries as in FIRST/ITEMS2 and SECOND/ITEMS2
where FIRST and SECOND are the library names. Can this be achieved in one query?
For those who have no understanding of iSeries: The above insert statement would be similar to having a insert query for 2 tables.
The INSERT statement does not support inserting into multiple tables.
However you could create a trigger on FIRST/ITEMS2 to automatically insert/update/delete the record into SECOND/ITEMS2.
See the CREATE TRIGGER statement for more information.
If this will be run often, consider making the INSERT into a stored procedure, and then setting the target schema via SET SCHEMA:
set schema=first;
call my_insert_proc(:scapp);
set schema=second;
call my_insert_proc(:scapp);
You could create a QMQuery like this
INSERT INTO &LIB/ITEMS2
(PROGRAM, VLDFILE, VLDFLD, SELFILE, SELFLD)
VALUES (&SCAPP, 'CSTMR', 'CYC', 'BYC', 'BYCC');
Then
STRQMQRY myQmQry SETVAR(('LIB' 'FIRSTLIB')('SCAPP' &VAR))
STRQMQRY myQmQry SETVAR(('LIB' 'SECONDLIB')('SCAPP' &VAR))
From IBM's Syntax diagram of INSERT ( http://pic.dhe.ibm.com/infocenter/iseries/v7r1m0/index.jsp?topic=%2Fdb2%2Frbafzbackup.htm ), I'd say you have to go with two queries.
But after the first time of executing this query, you can try changing the current library ( http://publib.boulder.ibm.com/infocenter/iadthelp/v7r1/topic/com.ibm.etools.iseries.langref2.doc/chglibl.html ).

SQL insert into with Hsqldb Script

I am trying to initialise my hsqldb with some default data but seem to be having a problem with identity and timestamp columns.
I just realised that I probably wasn't clear what I meant when I said "script". I am meaning the command line argument that you pass to hsqldb to generate your database at startup. I can successfully run the query inside DbVisualiser or some other database management tool.
I have a table with the following definition:
create table TableBob (
ID int NOT NULL identity ,
FieldA varchar(10) NULL,
FieldB varchar(50) NOT NULL,
INITIAL_DT timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL);
I can successfully create this table using the script but trying to insert a record doesn't work. Below is what I would consider valid sql for the insert since the ID and INITIAL_DT fields are Identity and Default columns). Strangely it inserts null into every column even though they are defined as NOT NULL....
e.g.
INSERT INTO TableBob (FieldA, FieldB) VALUES ('testFieldA', 'testFieldB');
Thanks for your help
Please try with HSQLDB's DatabaseManagerSwing (you can double click on the hsqldb.jar to start the database manager). First execute the CREATE TABLE statement, then the INSERT statement, finally the SELECT statement.
It should show the correct results.
If you want to use a script to insert data, use the SqlTool.jar which is available in the HSQLDB distribution zip package. See the guide: http://hsqldb.org/doc/2.0/util-guide/