Internal join in Insert query?

I want to 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 allowed

How to stop this error?

+3
source share
6 answers

Assuming you are using SQL Server:

insert into tableA 
  (val1, val2) 
select top 1 'value', tableB.x from tableB where tableB.Y = @y 
+9
source

I assume that you need to directly use the insert in the TABLE select syntax ....
In this case, there are no "values".
People above were faster than me, but I agree with their suggestions.

+1
source

:

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

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

, , : .

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

.

+1
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)");

.

?

//mssql server

0
source

Source: https://habr.com/ru/post/1734582/


All Articles