0

I am trying to insert the user id from table users inside table session , field session_user, using textbox , but it seems it doesn't work ..

Here is my SQL code, I am using visual studio and trying to insert to a SQL Server table

SqlCommand addsession = new SqlCommand
  ("insert into dbo.session(session_user) 
    values (select user_id from dbo.users where username = '" + TextBox1.Text + "')", 
   badersql);
2
  • 6
    xkcd.com/327 Commented Dec 11, 2010 at 18:34
  • 1
    And you SHOULD by all means use a parametrized query instead of concatenating together your INSERT statement...... Commented Dec 11, 2010 at 19:22

4 Answers 4

6

You shouldn't use the VALUES keyword when you're doing an INSERT ... SELECT:

insert into dbo.session (session_user) select user_id from dbo.users ...
Sign up to request clarification or add additional context in comments.

1 Comment

SqlCommand addsession = new SqlCommand(" insert into dbo.session (session_user) select user_id from dbo.users where username = '" + TextBox1.Text + "'", badersql); , i tried to do this but it gave me this error " Incorrect syntax near the keyword 'session_user'."
4

If you are inserting the result of a query into another table, just leave out the VALUES keyword.

The VALUES keyword can always be replaced by a simple SELECT 'dummy', 'value' of the values you want to insert, but I suggest you still use VALUES whenever you want to make it clear that your results do not come from a query.

That being said, please use parameterized queries!! Imagine if someone were to enter the following text into TextBox1:

' or 1 = 1

What would happen?

1 Comment

thanks for the tip , but this project is will be locally on my computer and it won't be used in the internet now or in the future, i know parametrized queries are the correct thing to do , but no need to use them right now , thanks again
2

To insert records from a query use this insert syntax:

insert into dbo.session (session_user) 
select user_id from dbo.users where username = '" + TextBox1.Text + "'

You may want to do a select top 1 userid if you are expecting one row to be inserted like in the values statement.

1 Comment

If you post code or XML, please highlight those lines in the text editor and click on the "code" button (101 010) on the editor toolbar to nicely format and syntax highlight it!
0

i did it , the problem was that i can not name my record session_user , so i replaced with se_user and that solve the problem .

thank u all for ur help

so the correct sql statement is

insert into sessions (se_user) select USER_ID from users where username = '';

Comments

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.