1

Two database tables: 1)Client (ClientID, Name) 2)Purchase (ClientID, Name)

Situation: Login page --> online purchase page (Session with username)

Problem: How can i make the SQL over different tables? I want to insert Clientno in Purchase tables when clients make purchase.

Fail SQL: ( The session is okay )

string id = Convert.ToString(Session["UserID"]);

string query1 = "insert int Purchase ([Clientno]) values('"+@clientno+"') where [select Clientno where name ='"+id+"')"; 
3
  • insert int, or insert into? Commented Apr 21, 2015 at 1:56
  • into but it seems not logically work Commented Apr 21, 2015 at 2:06
  • You need to share your specific error message etc. Commented Apr 22, 2015 at 1:14

1 Answer 1

1

You can insert the results of a select into a table without a VALUES clause, so the straight SQL would look something like this (I changed your query from Clientno to ClientID based on your table definitions up top):

INSERT INTO Purchase ([ClientID])
SELECT ClientID
   FROM Client
   WHERE Name = @ID

You really want to use parameterized queries though, and not build your SQL inline, like you are doing.

I don't know what other fields you might want to be inserting, but this is the general format of that sort of query.

Sign up to request clarification or add additional context in comments.

4 Comments

INSERT INTO Purchase ([ClientID] ) <-----------how to save it into a variable "ClientID"? SELECT ClientID FROM Client WHERE Name = @ID
DECLARE @ClientID int; SELECT @ClientID = ClientID FROM Client WHERE Name = @ID
um your insert SQL seems a little problem that i cannot function properly
You're going to need to give more description of the problem than that. I can assure you the syntax is valid - what part is not working for you?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.