tags:

views:

589

answers:

6

I wanna do something like this:

insert into TableA 
   (val1,val2) 
values
   ("value",(select top 1 tableB.X from tableB where tableB.Y=@Y))

I get this error:

Subqueries are not allowed in this context. Only scalar expressions are allowed

How to stop that error?

+7  A: 

Assuming you're using SQL Server:

insert into tableA 
  (val1, val2) 
select top 1 'value', tableB.x from tableB where tableB.Y = @y 
ristonj
+1: Beat me to it
OMG Ponies
Thanks for the formatting edit and the upvote :-)
ristonj
A: 

I assume you have to use directly the insert into TABLE select... syntax.
No "values" in this case.
People above have been faster than me but I agree with their proposals

PierrOz
A: 

You're close:

INSERT INTO TableA(val1, val2)
SELECT top 1 "value",  X FROM TableB WHERE Y = @y
Jacob G
A: 

try this

insert into TableA (val1,val2) 
   select top 1 "value",X from tableB where Y=@Y
SQLMenace
+1  A: 

Another, inferior option that's less code change: Define an interim value.

declare @scalarval int
select @scalarval = tableB.X from tableB where tableB.Y=@Y
insert into TableA (val1,val2) 
values("value",@scalarval)

However the insert into syntax is clearer.

Broam
Incorrect syntax nead top ??
I believe you are correct; I do not believe you can do top 1 select into a variable like that. Maybe select top 1?Fixed query.
Broam
A: 
StringBuilder sb=new StringBuilder();
sb.Append("declare @id int select @id = top 1 TableB.id from TableB where TableB.DefaultName=@DefaultName order by TableB.id desc insert into TableA(col1,col2,col3,col4)  Values (@val1,@val2,@val3,@id)");

incorrect syntax near top .

How to done with this ??

//mssql server