Basically I have 2 tables but the problem is I would like to insert data from table A column A to table B column C.
But when I try to this I get an error
My subquery is:
SELECT TOP 1 [Id]
From [A]
Where [B] = 'ValueCon'
And here is my insert query
INSERT INTO [B]
([BA]
,[BB]
)
VALUES
('TestData'
,(SELECT TOP 1 [Id]
From [A]
Where [AB] = 'ValueCon')
)
There is no need to worry about data types as they are all matching.
I get the following error:
Subqueries are not allowed in this context. Only scalar expressions are allowed.
I have seen many complex ways of getting around this but just need something simple.
May be if you use a declared param, you can use it to the INSERT
DECLARE @theInsertedId INT;
SELECT TOP 1 @theInsertedId=[Id]
From [A]
Where [B] = 'ValueCon'
INSERT INTO [B]
([BA]
,[BB]
)
VALUES
('TestData'
,@theInsertedId
)
Sorry for by bad english! Hope this help!
Read up on the proper syntax for INSERT
! It's all very well documented in the SQL Server Books Online ....
Either you have INSERT
and VALUES
and you provide atomic values (variables, literal values), eg
INSERT INTO [B] ([BA], [BB])
VALUES ('TestData', @SomeVariable)
OR you're using the INSERT ... SELECT
approach to select column from another table (and you can also mix in literal values), eg
INSERT INTO [B] ([BA], [BB])
SELECT
TOP 1 'TestData', [Id]
FROM [A]
WHERE [AB] = 'ValueCon'
but you cannot mix the two styles. Pick one or the other.
You could just have a single select statement?
Not sure if this will work for what you are trying to do....
declare @a table
(
ab varchar(20),
id varchar(20)
)
insert @a
select 'ValueCon',1
union all
select 'ValueCon',2
union all
select 'Con',100
declare @b table
(
ba varchar(20),
bb varchar(20)
)
insert @b (ba,bb)
select top 1 'TestData',id from @a where ab='Valuecon'
select * from @a
select * from @b
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.