INSERT INTO multiple rows with subquery

守給你的承諾、 提交于 2020-01-25 11:39:06

问题


I want to INSERT INTO by more than one value at a time, I did this by doing the following:

INSERT INTO table_1(col_1,col_2,col_3)
SELECT col_1, col2, (SELECT col3 FROM table_3)
FROM table_2

But col3 from table_3 is a datetime format, while col3 from table_1 needs an integer value. I did this by doing the following:

CAST(CONVERT(varchar(10),(SELECT col3 FROM table_3),112)AS int)

When I run this I get a more than one result in a subquery error. I have really no idea whatsoever on how to fix this. Hopefully you do.

Thank you in advance.


回答1:


INSERT INTO table_1(col_1,col_2,col_3)
SELECT col_1, col2, (CAST(CONVERT(varchar(10),(SELECT top 1 col3 FROM table_3),112)AS int))
FROM table_2

You need to use top 1 to select 1 row




回答2:


Well, I think the error says it all. You have to limit the inner query somehow with WHERE condition, with TOP or with MAX(col3) for example. Depends WHICH col3 you want.




回答3:


You need to join table_2 to table_3. Not sure what your database structure is, but it should be something like this:

INSERT INTO table_1(col_1,col_2,col_3)
SELECT t2.col_1, t2.col2, t3.col3 
FROM table_2 t2
INNER JOIN table_3 t3 on t3.t2id = t2.id

The alternative is to use TOP 1, to just return 1 record in the sub-query - but I would not recommend this as it may not be the value you want:

INSERT INTO table_1(col_1,col_2,col_3)
SELECT col_1, col2, (SELECT top 1 col3 FROM table_3)
FROM table_2



回答4:


You can use CTE to prepare your data :

;WITH MyData (col1, col2, col3)
AS
(
    SELECT col_1, col2, CAST(CONVERT(varchar(10),(col3),112)AS int)
    FROM table_2 JOIN table_3 ON <join condition>
)
INSERT INTO table_1(col_1,col_2,col_3)
SELECT col_1, col2, col3
FROM MyData



回答5:


Pls try below query :

INSERT INTO table_1(col_1,col_2,col_3)
SELECT col_1, col2, isnull((SELECT TOP 1 cast(col3 as int) FROM table_3),0)
FROM table_2


来源:https://stackoverflow.com/questions/25759512/insert-into-multiple-rows-with-subquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!