Bader
Bader

Reputation: 207

SELECT inside INSERT query?

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);

Upvotes: 0

Views: 1505

Answers (4)

Bader
Bader

Reputation: 207

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 = '';

Upvotes: 0

ClosureCowboy
ClosureCowboy

Reputation: 21531

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?

Upvotes: 4

Steve
Steve

Reputation: 2193

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.

Upvotes: 2

casablanca
casablanca

Reputation: 70691

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 ...

Upvotes: 6

Related Questions