How can I insert from multiple tables into one? - asp.net

I have a table for users (username, password .. etc) and another one for products (product name, price, quantity, username .. etc)
I want the username from the first table to be inserted (with the rest of the product info) into the product table when the user put it for sale.
How can I do this?
I'm using visual web developer 2008 express

INSERT INTO product_information (username,product_name, ...., Date)
SELECT username, 'Book',....., Date
FROM users;
something along that line

Your question doesn't exactly make sense. It sounds like you want to insert into one table (Products) and one of the fields is also in another table (User.username). Where does the rest of the data for Products come from? Can't you just insert the username directly?
Insert into products (name, price, username) values (?, ?, ?)
Use whatever mechanism you want to pass in the data to that SQL statement.
If, however, you actually have a third table, say, 'Prod_for_sale' and you want to insert a bunch of data into that table, from both Users and Products, you can do something like this (as suggested by Rick J, but this example has two tables):
insert into products for sale (username, user_country, product_name, product_price)
select u.username, u.country, p.name, p.price
from products p, users u
where p.id = ?
and u.username = ?
Then you can copy whatever data you want from the tables in question into the destination table.
A word of advice though: you should be using a user ID instead of a username to identify the user's data in the database. This will allow you to change your username policy later or allow for usernames to be updated, etc. Generally try to make all your identifiers numbers and you'll save yourself hassle in the future.

If you have Linq (.NET 3.5 / C# 3.0):
var users = from u in userTable
from p in productTable
where p.username = u.username
select new productDetails()
{
username = u.username,
price = p.price
}
then newtable.insertAllOnSubmit(users);
if in straight sql
insert into newtable
select table1.value1, table2.value1
from table1, table2
where table1.username = table2.username
Edit:
to clarify... value1 and value2 are columns from the corresponding cases. You'll have one for each parameter you want to insert. And your newtable becomes table1

Related

Selecting an id from database using razor pages?

I am the following. As a user registers his account name and password are put into an existing table. Then his id gets read from that table and another table is made using that id as the tablename.
Now inserting works great but reading the Id from that table seems to give me some problems.
Now it would be great if I was even able to get that id to display on my webpage. i feel like when I am able to do that I can just do something like CREAT TABLE + #Id + etc.
This is what I have so far
var gebruikersnaam = Request.Form["registnaam"];
var wachtwoord = Request.Form["registpassword"];
if (IsPost && Request.Form["registreren"] == "Registreren")
{
var insertCommand = db.Execute("INSERT INTO Accounts (gebruikersnaam, wachtwoord) VALUES(#0, #1)", gebruikersnaam, wachtwoord);
var id = db.Query("SELECT * FROM Accounts WHERE gebruikersnaam = #0", gebruikersnaam);
Response.Write(#id);
}
And this is what the Response.Write(#id) shows me on the webpage:
System.Collections.ObjectModel.ReadOnlyCollection`1[System.Object]
Try merging the create and select query into one.
INSERT INTO Accounts (gebruikersnaam, wachtwoord)
OUTPUT Inserted.Id
VALUES('value1', 'value2')
Getting the Id using a separate query could be a problem in the future especially if the data becomes large, doing this optimize the speed of data retrieval in DB like getting the Id of an inserted record.

Insert data where Multiple Foreign keys are in SQL server table

I have three Tables:
Teachers
PK: A_pk
Students
PK: B_pk
Post
PK: C_pk
FK: A_pk
FK: B_pk
I have a Website page where users write different posts.
When teachers post in that group, I will insert data into the Post table like this:
A_pk = teacherName
C_pk = Post_text
When students post in that group, I will insert data into the Post table like this:
B_pk = studentName
C_pk = Post_text.
Reason is that I want to keep record which user posted data in my group.
Now the Question is how to insert record in Post table?
You cannot have one field in your table be a foreign key to two different tables. What you need to do is change your data structure to either hold your students and teachers in the same table and use that primary key in your Post table, or to have two columns in your Post table - one for the Teacher primary key and one for the Student primary key and populate the appropriate one based on who made the post.
There is absolutely no need nor reason to have the ID of two different tables within the same field. Doing so would be bad design.
Finally--- I found the Solution.
Actually its very simple... Like you can have nullable FK.so when you insert for student then A_PK can be null and vice versa. –
If teacher posted data in group than
if(A_pk != null) { Insert A_pk and Insert C_pk }
If student posted data in group than
else if(B_pk != null) { Insert B_pk and Insert C_pk }
Thanks alot Sir
KumarHarsh 1 hour ago

SQL Return all rows if admin, otherwise return user records

When using SQL DataSource, I want to return the record essentially tied to the currently logged in user. I can do this, just fine.
But, when that logged in user is tagged as 'ADMIN' in the user table, I want to return all rows.
Fields:
Name
Address
databaseid
IsAdmin
ASP.net page sends #databaseid
SQL server returns Name and Address for #databaseid user only. Perfect!
but I want to return everything in the table if IsAdmin = 1 for that given databaseuserid.
I am using a SP to return records. Basically ignore the filter.
Can you modify the stored proc? If so, then change the select stmt:
SELECT Name, Address, databaseid, IsAdmin
FROM YourTableName
WHERE databaseid = #databaseid
OR 1 = (SELECT IsAdmin
FROM YourTableName
WHERE databaseid = #databaseid);

asp.net entity framework - Complicated Queries with join + Membership user

I have 2 tables.
Users - have userID, userMainGroup and userMinorGroup
Tasks - TaskId, UserId
My goal is:
I have current CurrentuserId and i want to show him all the tasks that were created by users from the same MainGroup as he.
In SQL i would write:
Select *
From Tasks Left join Users on tasks.Id=users.id
Where users.MainGroup=CurrentuserMainGroup; (var)
How do i do it using entity framework?
I understood that to make a join i need to write something like:
var tasks = from t in db.tasks
from u in db.users
where t.Id=u.Id
select new {t.Id, t.name....}
but where do i put the condition Where on the MainGroup?
you can try like this
var data= (from con in db.tasks
let UserMainGroup = db.users.where(x=>x.id==con.id).FirstOrDefault()
where UserMainGroup.MainGroup=CurrentuserMainGroup
select new {
ID=con.id,
Name=con.name
}).ToList();
i think this will help you.......
It is recommended that you use navigation properties in stead of manually coded joins:
from t in db.Tasks
where t.User.MainGroup == currentuserMainGroup
select new {t.Id, t.name.... , t.User.Name, ... }

Get the UserID of the current logged in User in asp.net default membership provider

I have two tables
Employee (EmpID, Name, UpdatedBy, UpdateDate)
EmpContact (ContactID, Contact,EmpID)
I am trying to create a trigger which update a Employee table fields UpdatedBy,UpdateDate. when contact is added or modified i want to update Employee's UpdatedBy and UpdateDate fields (These two tables have different asp.net-mvc views).
I am using default membership provider to authenticate the user. So my question is how can i get the current logged in user in trigger who initiated the insert, update or delete. Is there any way i can know which asp.net user id initiated the transaction within the TRIGGER
Create an insert/update/delete trigger that updates the Emplyoee table when records in EmpContact are created/updated/deleted, for example(insert):
CREATE TRIGGER [dbo].[trgCreateEmpContact] ON [dbo].[EmpContact]
FOR INSERT
AS
UPDATE dbo.Employee
SET UpdateDate=GetDate(), UpdatedBy = I.UpdatedBy
FROM Employee E
INNER JOIN Inserted I ON E.EmpID = I.EmpID
So you need to add the UpdatedBy column to your EmpContact table too.
You get the current logged in user in the following way:
MembershipUser currentUser = Membership.GetUser();
GUID currentUserID = (GUID)currentUser.ProviderUserKey;
Another(better) approach would be to create a stored-procedure that internally creates the EmpContact record and updates the Employee table in a transaction, for example(untested):
CREATE PROCEDURE [dbo].[InsertEmpContact]
#ContactID int OUTPUT,
#Contact varchar(50) OUTPUT,
#EmpID int OUTPUT,
#UpdateDate datetime OUTPUT,
#UpdatedBy int OUTPUT,
with execute as Owner
AS
BEGIN TRANSACTION
INSERT INTO EmpContact(Contact, EmpID)
VALUES (#Contact,#EmpID)
;SELECT #ContactID=ContactID,#Contact=Contact,#EmpID=EmpID,#UpdateDate=GetDate()
FROM EmpContact WHERE (ContactID = SCOPE_IDENTITY())
;UPDATE dbo.Employee
SET UpdateDate=#UpdateDate, UpdatedBy = #UpdatedBy
WHERE EmpID = #EmpID
IF ##ERROR <> 0
BEGIN
-- Rollback the transaction
ROLLBACK
RETURN
END
COMMIT
If you want to detect the current logged in user from memebership please use these links
http://www.codeproject.com/KB/aspnet/CustomMembershipProviders.aspx
http://theintegrity.co.uk/2010/11/asp-net-mvc-2-custom-membership-provider-tutorial-part-2/
It depends on how your app connects to your database. If you do it, like almost all of us, with connection pooling and a single user connecting to the database, the answer is no, you cannot know that in the trigger.
E.g. the app connects to the database as sa/pwd (not advisable, but for arguments sake only).
If user one (Paul) connects to the db and does an update, your trigger will get sa as user.
If user two (Anne) connects to the db, the trigger will also get sa as user.
So you need to include the update of the user in the update statmement (or as an argument to your stored procedure)

Resources