Inner join in Insert query?
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?
Assuming you're using SQL Server:
insert into tableA
(val1, val2)
select top 1 'value', tableB.x from tableB where tableB.Y = @y
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
You're close:
INSERT INTO TableA(val1, val2)
SELECT top 1 "value", X FROM TableB WHERE Y = @y
try this
insert into TableA (val1,val2)
select top 1 "value",X from tableB where Y=@Y
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.
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
精彩评论