将select的输出写入表中

时间:2012-09-19 09:20:14

标签: sql-server

我有这样的声明:

 insert into Admin.VersionHistory --do not know what to put here
 select COUNT(*) as cnt
 from membership.members as mm 
 left join aspnet_membership as asp
 on mm.aspnetuserid=asp.userid 
 left join trade.tradesmen as tr 
 on tr.memberid=mm.memberid  
 where asp.isapproved = 0 and tr.ImportDPN IS NOT NULL and tr.importDPN <> ''

它总共给了我179956.我想把这个总数写成另一个叫Admin.VersionHistory的表,它有id(autoinc),version(varchar)和date(sysdate)列,

我该怎么办? 感谢

3 个答案:

答案 0 :(得分:1)

您的查询返回带有一列和一行的结果集。它可以插入到一个具有一个整数列的表中。您的目标表不适用于此,因为它有三列。

答案 1 :(得分:0)

你应该可以这样做:

INSERT INTO Admin.VersionHistory(ColumnName) 
SELECT COUNT(*)
-- the resut of your query here

答案 2 :(得分:0)

INSERT INTO Admin.VersionHistory (ColCount, version, Sysdate)
VALUES(  

(SELECT COUNT(*) AS cnt  FROM membership.members AS mm     
lLEFT JOIN aspnet_membership AS asp ON mm.aspnetuserid = asp.userid   
LEFT JOIN trade.tradesmen AS tr ON tr.memberid=mm.memberid   
WHERE   
asp.isapproved = 0 AND   
tr.ImportDPN IS NOT NULL AND   
tr.importDPN <> ''),   
VERSIONVALUE, GETDATE())  

虽然我在Oracle中尝试过类似的东西,但我猜它在SQL中应该没有什么不同。

试一试。