Table JOIN With INSERT Statment
May 11, 2008How to perform a table JOIN with the INSERT SQL statment, just show a join example between 2 tables will do.
View 2 RepliesHow to perform a table JOIN with the INSERT SQL statment, just show a join example between 2 tables will do.
View 2 RepliesHow to perform a table JOIN with the INSERT SQL statment, just show a join example between 2 tables will do.
View 3 Replies View Related
Hi all
I have two tables I need to Select the record from the First table and insert them into the second table and delete the record from the first table how can i do that with the SQL Statment?
Thank you in advance .....
Regards,
sms
Will writes "I have an employees table, which gives all emp. ids. I have a second table, time_log with tasks each employee has logged:
empID date log_time duration etc
===================================
and a 3rd table - a pivot table with a single column named "i" containing consecutive integers from 0 - 1000
I need to know for each date in a series, e.g seven consecutive days, how much time each has logged. easy if everyone has logged a task for every day, but I need to include every day where they have not logged a task.
so, a cartesian join on all the dates in a series(produced using dateadd on p.i and the pivot table)
SELECT dateadd('d',p.i, #02/19/2007#), e.empID
FROM pivot1 p, employees e
WHERE i<no_dates
However I need to do a left join with time log where the date and employee ids are the same, and I have summed the durations for each date. The following query does this, but does not include dates and times where nothing has been logged.
SELECT empID, log_date, sum(duration)
FROM time_log
GROUP BY empEIN, log_date
GIVING, EVENTUALLY, ALL DATES AND EMPIDS AND THE TOTAL AMOUNT OF TIME THEY HAVE LOGGED FOR EACH DAY."
Is it possible to insert data into a table from a temporary table that is inner join?
Can anyone share an example of a stored procedure that can do this?
Thanks,
xyz789
i have 3 tables in sql the relation between them is one to one
person ==> employee ==> sales_department_stuff&
another relation ( one to one )between
person(the same as above ) ==> customer
i want to put person id in employee not repeated in customer becase all (employee and customer is a person )
sooooooo
i put this sql statment to try to insert person id in employee then in sales_department_stuff table to complet his ordersinsert into Person (Person_Name_Ar,Person_Name_En) values ('aaaaa',' ssssssss')select @@identity from Personinsert into Employee values (@@identity,'1') select @@identity from Personinsert into sales_department_Staff values (@@identity,'1')select @@identity from Personinsert into Driver values (@@identity,'2','2222','1/1/2005','5') /* SET NOCOUNT ON */
RETURN
the first 3 statment is run and success
but underline stetment return error that
he can insert null value in id field ,,,,,,,,,,,,,,,,
he can compile @@identity in these statment ??????????????
plz help me
Hi All,
I have a table "Person" that has two columns "FirstName" and "LastName".
How can I insert multiple rows into this table using the INSERT stsmt.
I want to use just one insert statement.
Thanks in advance,
Vishal S
Hello, How can I do something like:
Insert Into Displayed(snpshot_id, user_id, user_domain, ddisplay, iWidth, iHeight, disp_size, disp_format, watermark, frc_update, creditcost)
Values ((Select snpsht_id from SiteIndex Where user_domain like '%domain'), 1000, (Select domain_id from UserDomains Where user_domain like 'domain'), GetDate(), 480, 360, 2, 1, 1, 0, 3)
Im getting an error:
Subqueries are not allowed in this context. Only scalar expressions are allowed.
Thanks!
I have two tables that have a one-to-one relationship. The reason they are two table is that one table has user data, whereas the other table has security information. The security information will be in a different security zone.
How do I do an insert into the two tables so that I do not get an integrity error?
I know this is a sin in dbforums to jump forums to ask other forum questions, but I just had to do it.....
it's actually related to foxpro dbf tables. Here is the case:
I am opening this existing DBF file in Microsoft Visual Fox Pro 6.0 .
In the command window, select, update and even including delete statements works .
What is getting on my nerves is the "insert" statement. It always prompts "syntax error". But the @#$@#$ error message just didn't help much.
The funny thing is, if I use the "Append Mode" and add data directly via the GUI, it works!.
Here is the insert statement, just a very simple one:
<code> INSERT INTO ASSET (ACCNO) values '2000/141'</code>
You can reply me here , or go to the real thread to reply me if you can help out..thanks
http://www.dbforums.com/t1058508.html
Hello,
I have a table (SQL Server 2000) which contains data and I want to create insert statements based on this data. The reason for this is to create a .sql file to run this against another database to insert the same data. I know I can do an import but was trying to do this via a .sql script. Is there any way to generate these insert statement automatically using some SQL tool?
Thanks
Hi, I'm having problems passing a querystring from the datanavigateurlformatstring to be used in a insert sp on a webform. Please can someone take a look at my code and point me in the right direction. At the moment I'm gettingthis error messageCompiler Error Message: BC30451: Name 'userid' is not declared. but in the url i can see the querystring I've passed from the previous page.
Thanks in advance Dave
1 Protected Sub Execute_Clicked(ByVal sender As Object, ByVal e As EventArgs)
2
3 Dim objConn As New System.Data.SqlClient.SqlConnection()
4 objConn.ConnectionString = "My connection string"
5 objConn.Open()
6 Dim objCmd As New System.Data.SqlClient.SqlCommand("test_insert", objConn)
7 objCmd.CommandType = System.Data.CommandType.StoredProcedure
8
9
10 Dim puserid As System.Data.SqlClient.SqlParameter = objCmd.Parameters.Add("@userid", System.Data.SqlDbType.Int)
11 Dim pdate As System.Data.SqlClient.SqlParameter = objCmd.Parameters.Add("@date", System.Data.SqlDbType.DateTime)
12 Dim papplicants As System.Data.SqlClient.SqlParameter = objCmd.Parameters.Add("@applicants", System.Data.SqlDbType.Int)
13 Dim pclients As System.Data.SqlClient.SqlParameter = objCmd.Parameters.Add("@clients", System.Data.SqlDbType.Int)
14 Dim pcontacts As System.Data.SqlClient.SqlParameter = objCmd.Parameters.Add("@contacts", System.Data.SqlDbType.Int)
15
16
17
18
19
20 puserid.Direction = System.Data.ParameterDirection.Input
21 puserid.Value = Convert.ToInt32(userid.QueryString)
22 pdate.Direction = System.Data.ParameterDirection.Input
23 pdate.Value = Convert.ToDateTime([date].Text)
24 papplicants.Direction = System.Data.ParameterDirection.Input
25 papplicants.Value = Convert.ToInt16(applicants.Text)
26 pclients.Direction = System.Data.ParameterDirection.Input
27 pclients.Value = Convert.ToInt16(clients.Text)
28 pcontacts.Direction = System.Data.ParameterDirection.Input
29 pcontacts.Value = Convert.ToInt16(contacts.Text)
30
31
32
33 command.ExecuteNonQuery()
34
35
36 objConn.Close()
37
38 End Sub
Hi all
i'm using sqlserver 2005
this statment take 1:30 min to execute
****insert into temotable (select key from table1)
if i used a select statment alone it takes 4 sec
but with insert statment it take 1:30min
by the way i put indexes on the table1
plz how i can increase the speed of insert statment.
thanks in advance
Hi
i m trying to call a function in insert statment
Insert Into (value, value1)
Value(@value, dbo.function(@value1)
dbo.function returns a value,
when i test the function in querry builder all goes fine.
In my program i become a error
"Parameterized Query '' ' expects parameter @value1 , which was not supplied."
I m using visual studio , tableadapter.update function to insert datarecords in db
thx for help
Hi
Simple statment is giving me a logout on the server
INSERT INTO Angebot (Nummer,Variante,Bearbeiter,Datum,Geld,Kurs,Language,Flag,AngebotStatus,TStatus)
VALUES (90360,3,'Admin',DEFAULT,'CPI_BE-D',1,'CPI_AG-1',4,NULL,59)
The statment works fine on production, however i have played a backup from production to my laptop to test something and as soon as I add a record to the database my connection to the database is droped (the data is not added to the table).
the error message I get is double, however I execute the statement only once.
Msg 0, Level 11, State 0, Line 0
Für den aktuellen Befehl ist ein schwerwiegender Fehler aufgetreten. Löschen Sie eventuelle Ergebnisse.
Msg 0, Level 20, State 0, Line 0
Für den aktuellen Befehl ist ein schwerwiegender Fehler aufgetreten. Löschen Sie eventuelle Ergebnisse.
Sugestions anyone?
PS: the message in English is:
Msg 0, Level 20, State 0, Line 0
A severe error occurred on the current command. The results, if any, should be discarded.
I would like to compare values in the same table and get the single record with different values in the multiple columns.For table tab1, ID is my key column. If type1 is active (A) then i need to update X else blank on Code1 column and if type2 is active (A) then i need to update X else blank on code2 column. Both type1 and type2 comes from same table for same ID..Below is the example to understand my scenario clearly....
declare @tab1 table (ID varchar(20), dt date, status varchar(1), type varchar(10))
insert into @tab1 values ('55A', '2015-07-30', 'A', 'type1')
insert into @tab1 values ('55A', '2015-07-30', 'C', 'type2')
insert into @tab1 values ('55B', '2015-07-30', 'C', 'type1')
insert into @tab1 values ('55B', '2015-07-30', 'A', 'type2')
[code]....
I can think of ways to resolve this issue, but I am wondering if there is a standard practice or some setting that is used to ensure that text containing a single quote, such as "Bob's house", is passed correctly to the database when using a SqlDataSource with all of the default behavior.
For example, I have a FormView setup with some text fields and a SqlDataSource that is used to do the insert. There is no code in the form currently. It works fine unless I put in text with a single quote, which of course messes up the insert or update. What is the best way to deal with this?
Thank you
I have table A (EmployeeNumber, Grouping, Stages)
and
Table B (Grouping, Stages)
Table A could look like the following where the multiple employees could have multiple types and multiple stages.
EmployeeNumber, Type, Stages
100, 1, Stage1
100, 1, Stage2
100, 2, Stage1
100, 2, Stage2
200, 1, Stage1
200, 2, Stage2
Table B is a list of requirements that each employee must have. So every employee must have a type 1 and 2 and the associated stages listed below.
Type, Stage
1, Stage1
1, Stage2
2, Stage1
2, Stage2
2, Stage3
2, Stage4
So I know that each employee should have 2 Type 1's and 4 Type 2's. I hope that makes sense, I'm trying to change my data because ours is very proprietary.
I need to identify employees who do not have all their stages and list the stages they are missing. The final report should only have employees and the associated missing types and stages.
I do a count by employee to see how many types they have to identify the ones that don't have all the types and stages.
My count would look something like this:
EmployeeNumber Type Total
100, 1, 2
100, 2, 2
200, 1, 1
200 1, 2
So I know that employee 100 should have 2 more Type 2's and employee 200 should have 1 more Type 1 and 2 more Type 2's based on the required list.
The problem I'm having is taking that required list and joining to my list of employees with missing data and pulling from it the types and stages that are missing by employee. I thought I could get a list of the employees that are missing information and right join it to the required list where the missing records would be nulls. But, that doesn't work because some employees do have the required information and so I'm not getting any nulls returned.
How we can stop alter statement of Table when the Table is referred by Stored Procedures and other Objects?
View 1 Replies View RelatedI was writing a query using both left outer join and inner join. And the query was ....
SELECT
S.companyname AS supplier, S.country,P.productid, P.productname, P.unitprice,C.categoryname
FROM
Production.Suppliers AS S LEFT OUTER JOIN
(Production.Products AS P
INNER JOIN Production.Categories AS C
[code]....
However ,the result that i got was correct.But when i did the same query using the left outer join in both the cases
i.e..
SELECT
S.companyname AS supplier, S.country,P.productid, P.productname, P.unitprice,C.categoryname
FROM
Production.Suppliers AS S LEFT OUTER JOIN
(Production.Products AS P
LEFT OUTER JOIN Production.Categories AS C
ON C.categoryid = P.categoryid)
ON
S.supplierid = P.supplierid
WHERE
S.country = N'Japan';
The result i got was same,i.e
supplier country productid productname unitprice categorynameSupplier QOVFD Japan 9 Product AOZBW 97.00 Meat/PoultrySupplier QOVFD Japan 10 Product YHXGE 31.00 SeafoodSupplier QOVFD Japan 74 Product BKAZJ 10.00 ProduceSupplier QWUSF Japan 13 Product POXFU 6.00 SeafoodSupplier QWUSF Japan 14 Product PWCJB 23.25 ProduceSupplier QWUSF Japan 15 Product KSZOI 15.50 CondimentsSupplier XYZ Japan NULL NULL NULL NULLSupplier XYZ Japan NULL NULL NULL NULL
and this time also i got the same result.My question is that is there any specific reason to use inner join when join the third table and not the left outer join.
I'm having trouble with a multi-table JOIN statement with more than one JOIN statement.
For each order, I need to return the following: CarsID, CarModelName, MakeID, OrderDate, ProductName, Total ordered the Car Category.
The carid (primary key) and carmodelname belong to the Cars table.
The makeid and orderdate belong to the OrderDetails table.
The productname and carcategory belong to the Product table.
The number of rows returned should be the same as the number of rows in OrderDetails.
I have one control table to store all related table name
Table ID TableName
1 TableA
2 TableB
In Table A:
RecordID Value
1 1
2 2
3 3
In Table B:
RecordID Value
1 1
2 2
3 3
How can I get the result by select the Table list first and then combine the data in table A and table B?
Thank you!
Hi,My GIS software has a tool to count the number of points within agrid.This is fine for small recordset, when you get into the tens thousandsitbecomes unfriendly.It must be possible (more efficent??) to do a select statement fromthe two tables and insert the result into a column??Table Property has thousands of records that fall within each recordof Table Ward.Expect the SQL would beSELECT [Property].BedRmNumber FROM [Ward].LAWHERE [Property].LA = [Ward].LASurely this would need a loop.Could anyone help???Thanksclive
View 5 Replies View Relateddeclare @errors table (
erroriD varchar (20),
errorMessage varchar (100))
insert @errors select '1', 'unable to resolve address'
----------------------------------------------------------------------------------------------------------------------------------------
declare @addressLookup table (
address varchar (100))
insert @addressLookup
select'water'union all
select'apple'
----------------------------------------------------------------------------------------------------------------------------------------
declare @exception table (
address varchar (100),
errorID varchar (100))
----------------------------------------------------------------------------------------------------------------------------------------
declare @address table (
addressName varchar (100)
)
insert @address
select 'route 50 st'union all
select 'pine heaven st'union all
select 'banana st' union all
select 'apple st' union all
select 'sand st'
----------------------------------------------------------------------------------------------------------------------------------------
insert @exception (address, errorID)
select substring(a.addressName, 1, charindex(' ', a.addressName)), e.errorID
from @address a, @errors e
where substring(a.addressName, 1, charindex(' ', a.addressName)) not in
(select address from @addresslookup al)
and e.errorID ='1'
select * from @exception
----------------------------------------------------------------------
If the addressName is not in the @addressLookUp table. This addressName should be insert into the @exception table with the correct errorID from @errors.
i wrote the code but 'Pine heaven' and 'route 50 'is not showing.
table2 is intially populated (basically this will serve as historical table for view); temptable and table2 will are similar except that table2 has two extra columns which are insertdt and updatedt
process:
1. get data from an existing view and insert in temptable
2. truncate/delete contents of table1
3. insert data in table1 by comparing temptable vs table2 (values that exists in temptable but not in table2 will be inserted)
4. insert data in table2 which are not yet present (comparing ID in t2 and temptable)
5. UPDATE table2 whose field/column VALUE is not equal with temptable. (meaning UNMATCHED VALUE)
* for #5 if a value from table2 (historical table) has changed compared to temptable (new result of view) this must be updated as well as the updateddt field value.
I want to insert into a table the result of a select which contains a join. Is this possible in any way on mysql 3.23.58?
I tryed the following code (in both ansi 92 and non ansi 92 forms)
insert book_edition (ISBN, book_title, publisher, book_image, author_name)
select i.isbn, i.imageurl, i.author, i.title, i.publisher
from ImportDataUniqueISBN i
left outer join book_edition b
on i.isbn = b.ISBN
where b.ISBN is null
I get the following error:
INSERT TABLE 'book_edition' isn't allowed in FROM table list
If executed without the join statement it works well.
Tks!
Hello,
I have to load 2 flat file of 2 Gb each in a table. I found 2 ways to do that:
- Either I read my 2 file in parallels and I use a merge join transformation to merge my data. Then I load theses datas in my destination table
- Or I insert all my first file in the destination table then I read the second file and update my table with the new information.
Based on your experience, what is the best ? I'm running the first way for more than 30 minutes and SSIS is still sorting my datas.... (sort before the merge join)
Thanks in advance,
Knid regards
Hi,
I have two tables. Employees and departments as follows:
Employees
- Name
- Salary
- Department ID
Departments
-Department ID
-Department Name
Now what I am doing is that I am allowing the user to give me a CSV file with all the employees data to bulk insert it in the table Employees as follows:
Employee Name, Salary, Department Name
The problem is that the users know nothing about the department ID. So what they type in the CSV ffile as you can see above is the department name.
The SQL statement I normally use for bulk insert is:
BULK INSERT CAS.dbo.employees
FROM 'c:list.csv' WITH
(FIELDTERMINATOR = ',', ROWTERMINATOR = '' )
My question is, how can I use the same technique but insert the departments IDs not name as in the CSV file.!!!!
Appreciate your help.
Thanks
I have been working on this for a little bit and have gotten to this point. Below is the query in blue, the error in red. Now, from what I gather the error is telling me I can't insert a duplicate product code into tblProduct. Isn't that what the left join is exactly not doing, as in, the left join is inserting all records from Complete_records into tblProduct where the code is null(does not exist) in tblProduct? Or, is this an issue where the identity number, productID in tblProduct, isn't starting at the next number in turn?
Thanks.
Set Identity_Insert tblProduct on
DECLARE @MaxId int
SELECT @MaxID=MAX(productID)
FROM tblProduct
SELECT IDENTITY(int,1,1) AS ID,Complete_products.APNum, Complete_products.Title, Complete_products.CategoryID, Complete_products.Mountable, Complete_products.price,
Complete_products.Height, Complete_products.Width, Complete_products.IRank, Complete_products.frameable, Complete_products.Typ INTO #Temp
FROM Complete_products LEFT OUTER JOIN
tblProduct AS tblProduct_1 ON Complete_products.APNum = tblProduct_1.productCode
where tblProduct_1.productCode IS NULL
INSERT INTO tblProduct
(productID,productCode, productName, productNavID, CanBeMounted, productRetailPrice, productHeight, productWidth, Rank, CanBeFramed, ProductType)
SELECT @MaxID + ID, APNum, Title, CategoryID, Mountable, price,
Height, Width, IRank, frameable, Typ
FROM #Temp
(236752 row(s) affected)
Msg 2601, Level 14, State 1, Line 13
Cannot insert duplicate key row in object 'dbo.tblProduct' with unique index 'IX_tblProductt_productCode'.
The statement has been terminated.
Hi all,can somebody help to write this stored procedure Table1 Table2LogID MigIDUserMove LogIDUserNew Domain User The two tables are inner join with LogID.If in Table2 LogID=NULL then create new dataset in Table1 (INSERT)and then Update LogID in Table2IF in Table2 LogID= 2 (or something else) then update the dataset in Table1 with the same LogID Thanks
View 1 Replies View RelatedI have table 'stores' that has 3 columns (storeid, article, doc), I have a second table 'allstores' that has 3 columns(storeid(always 'ALL'), article, doc). The stores table's storeid column will have a stores id, then will have multiple articles, and docs. The 'allstores' table will have 'all' in the store for every article and doc combination. This table is like the master lookup table for all possible article and doc combinations. The 'stores' table will have the actual article and doc per storeid.
What I am wanting to pull is all article, doc combinations that exist in the 'allstores' table, but do not exist in the 'stores' table, per storeid. So if the article/doc combination exists in the 'allstores' table and in the 'stores' table for storeid of 50 does not use that combination, but store 51 does, I want the output of storeid 50, and what combination does not exist for that storeid. I will try this example:
'allstores' 'Stores'
storeid doc article storeid doc article
ALL 0010 001 101 0010 001
ALL 0010 002 101 0010 002
ALL 0011 001 102 0011 002
ALL 0011 002
So I want the query to pull the one from 'allstores' that does not exist in 'stores' which in this case would the 3rd record "ALL 0011 001".
I am using stored procedure to load gridview but problem is that i am not getting all rows from first table[ Subject] on applying conditions on second table[ Faculty_Subject table] ,as you can see below if i apply condition :-
Faculty_Subject.Class_Id=@Class_Id
Then i don't get all subjects from subject table, how this can be achieved.
Sql Code:-
GO
ALTER Proc [dbo].[SP_Get_Subjects_Faculty_Details]
@Class_Id int
AS BEGIN
[code] ....
If I join Table1 to Table2 with a WHERE condition, isit the same if I would join Table2 to Table1 consideringthat the size of the tables are different.Let's assume Table2 is much bigger than Table1.I've never used MERGE, HASH JOINs etc, do any ofthese help in this scenario?Thank you
View 3 Replies View Related