简体   繁体   English

SQL Server 2005-插入并选择1个值

[英]SQL Server 2005 - Insert with Select for 1 Value

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. 基本上我有2个表,但问题是我想将数据从表A列A插入到表B列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 可能是如果使用声明的参数,则可以将其用于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 ! 阅读有关INSERT的正确语法 It's all very well documented in the SQL Server Books Online .... 所有这些在SQL Server联机丛书中都有很好的记录。

Either you have INSERT and VALUES and you provide atomic values (variables, literal values), eg 要么具有INSERTVALUES要么提供原子值(变量,文字值),例如

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 ... SELECT方法从另一张表中选择列(也可以混合使用文字值),例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM