If i insert records in table T1, using output I want to insert these records from logical table 'inserted' into table T2. Below is my code. If I use the below code records get inserted into T2 but table T1 shows blank...can someone tell me where I am going wrong..
create table T1(id int identity(1,1), name vachar(100))
create table T2(id int, name varchar(100))
declare #t table(id int,name varchar(100))
insert into t1(name)
output inserted.id,inserted.name into #t
values('deepak')
insert into t2
select * from #t
this is strange ..If I do
select * from t1
select * from t2
I get value 'deepak' inserted in table T2 and table T1 shows blank.How to insert a record in both the tables T1 and T2 at the same time without using triggers.
A good way to get traction on your problem is to utilize a tool like SQLFiddle. Makes it easy to share and get others looking at your problem quickly :)
SQLFiddle Output Test
That seems to work for me, although I did see the issue you had with the same exact code you had above. Not sure if it's something related to temp tables, but there's definitely something weird happening.
Related
don't know if it's possible or not, but I'm wondering if I can automate the insertion of MySQL table2 depending on table1
Let's say I've two tables ( table1 and table2 ) in my database. and what I want is an automation, which will automatically create a new row in table2 with some default values whenever a new row is created in table1. so that I don't have to write insertion code for table2 in my PHP file
Don't know if I've made it enough clear. let me brief my table structure in a nutshell...
table1 :-
user_name ( unique )
user_email
table2 :-
user_name ( same as table1 )
is_account_active ( true as default )
invested ( 0 as default )
current_balance( 0 as default )
so whenever an account is created, I'm inserting new data both in table1 and table2. so I'm wondering if I can create the table2 in a specific way that whenever a new row is created in table1, table2 will automatically pull user_name from table1's new row and insert it in its own storage ( the rest of the column data are static. so I can set defaults for 'em )
[ NOTE: I need to keep 'em in two different tables as there'll be many columns in each table ]
<-- I know many of you'll ask for what I tried. but tbh I don't even have any idea what to try -->
You can use a AFTER INSERT TRIGGER
DELIMITER $$
CREATE TRIGGER after_table1_insert
AFTER INSERT
ON table1 FOR EACH ROW
BEGIN
IF NEW.user_name IS NOT NULL AND NEW.user_email IS NOT NULL THEN
INSERT INTO table2 (user_name,is_account_active, invested, current_balance)
VALUES(NEW.user_name,1,0,0);
END IF;
END$$
DELIMITER ;
You need to add all columns that you want to use in table2 with NEW.column_name
I need to Need to fetch all the records of table "#Tbl1" which "DisplayId" not present in table "#Tbl2".
"#Tbl1" having Max 100 records
"#Tbl2" is growing table
Create Table #Tbl1(Id1 Int Identity(1,1), DisplayId Nvarchar(200), Name Nvarchar(200))
Insert Into #Tbl1(DisplayId, Name) Values ('d1', 'ABC'),('d2', 'PQR')
Create Table #Tbl2(Id2 Int Identity(1,1), DisplayId Nvarchar(200))
Insert Into #Tbl2(DisplayId) Values ('d1')
Below query is working, but looking for efficient query and please suggest what kind of Index is required to which table's column?
I am using SQL Server 2008 R2
Select * From #Tbl1
Where DisplayId Not In (Select DisplayId From #Tbl2)
Using the in statement does seem to be slow generally, I would use an exists statement if possible but I'm not sure if it is supported on SQL Server 2008. Other option you have is a left join which will also be slow.
An exists or (not exists) statement works like this
select * from #tbl1 t1
where not exists (select displayid from #tbl2 where displayid = t1.displayid)
Notice the use of the alias t1, you do not have to select a column in the sub select, you can use a wildcard *. I've found this type of query is far more efficient because it uses the index links directly between the 2 tables instead of first selecting all the columns and then filtering them.
I am trying to populate a table with a subset of data from a select query and I want this table to be recreated at regular intervals.
I tried to create an event which inserts records but it duplicates the records.
I then tried to drop and then create the table in an event but it tells me the table already exists
This is what I am trying to achieve:
DROP TABLE IF EXISTS tablea;
CREATE TABLE tablea;
INSERT INTO tablea
SELECT * from tableb WHERE etc.
What is the proper way to achieve this?
are you in the right schema? I ask as your drop table command is fine and if you are in the right schema (use whateverdb;), it will work.
Your commands all look ok if they are summarised.
if tablea exists in your current schema:
drop table if exists tablea;
is fine
to create a table, you need to specify the fields eg.
create table tablea (column1 varchar(20), column2 int, etc etc);
or better still, if the tables are the same structure, you could ignore that part and create the table with a create table like statement:
drop table if exists tablea;
create table tablea like tableb;
insert into tablea select * from tableb where column1 = whatever;
If tablea doesn't need the same properties as tableb, you can even do:
drop table if exists tablea;
create table tableb as select * from tableb where column1 = whatever;
The only disadvantage of this method over the stament above it is that it will not carry through the defined keys and special properties (if there are any).
And finally, if you are going to be recreating tablea over and over again, then, after you have initially created tablea (create table tablea like tableb; ) you can just keep rerunning these two lines below:
truncate tablea;
insert into tablea select * from tableb where whatever;
will be best as truncate (empty the contents) is much quicker than drop and leave your keys/properties in tact.
I have a large table I am trying to add a field to, so far it has been much more efficient due to the table sizes I am working with to do
CREATE TABLE A LIKE B;
INSERT B SELECT * FROM A;
When making changes vs doing any Alter Table (Index, FIelds, etc.)
However if I do
CREATE TABLE A LIKE B;
Alter TABLE B ADD Fieldx varchar(100);
INSERT B SELECT * FROM A;
I cannot do that anymore as I get a field count mismatch. Clearly I can "just" do:
CREATE TABLE A LIKE B;
Alter TABLE B ADD Fieldx varchar(100);
INSERT Into B(Field1,..,FieldN) SELECT Field1,...,FieldN FROM A;
However I am trying to do this with a large # of tables each of which has a large # of fields and I've already got a good batch process that works with * and would be much much harder to try to explicitly push each field for each table into each Insert and Select.
Is there any way to express the
INSERT B SELECT * FROM A;
When B now has 1 more column than A in a way that will not return a count error?
As long as the new column is added to the end of the original columns, you can do:
INSERT INTO B
SELECT *, ""
FROM A;
I have crate a db in MySQL which has a lot of tables. I want the value of one table to be automatically saved on another table too.
For example I write something on: table1.lastname, I want this to be also stored in table2.lastname .
How is this called and how I can do that with PHP My Admin?
CREATE TABLE new_table_name LIKE old_table_name
Create trigger after_insert on new_table
like this
CREATE TRIGGER `AFTER_INSERT` AFTER INSERT ON `new_table_name` FOR EACH ROW BEGIN
insert into new_table_name (column_names) values (column_values) ;
END
For first you must create table for data store.
Then you must create trigger on wanted table for catch event and insert data in early created table.
This will do what you want:
INSERT INTO table2 (lastname)
SELECT lastname
FROM table1
If you want to include all rows from table1. Otherwise you can add a WHERE statement to the end if you want to add only a subset of table1.
I hope this helps.
If the table doesn't exist, you can create one with the same schema like so:
CREATE TABLE table2 LIKE table1;
Then, to copy the data over:
INSERT INTO table2 SELECT * FROM table1
Or If the tables have different structures you can also:
INSERT INTO table2 (`col1`,`col2`) SELECT `col1`,`col2` FROM table1;
EDIT: to constrain this..
INSERT INTO table2 (`col1_`,`col2_`) SELECT `col1`,`col2` FROM
table1 WHERE `foo`=1