使用OUTPUT INTO子句

时间:2015-03-04 17:05:41

标签: sql sql-server group-by

我正在使用OUTPUT INTO to子句从临时表dbo.Cache向表#Temp2插入某些列。值通过#Temp2语句插入select

我希望分组数据只能插入dbo.Cache而不是#Temp2。这是我的查询到目前为止,但分组依据是错误的地方。此外,我意识到OUTPUT子句中不允许聚合。我得到语法错误。请问有解决方法吗?

INSERT INTO #Temp2 (RowNumber, ValFromUser, ColumnName, ValFromFunc, FuncWeight, percentage)
OUTPUT INSERTED.ValFromUser, INSERTED.ColumnName, INSERTED.RowNumber, MAX(INSERTED.ValFromFunc)
INTO dbo.CACHE (StringSearched, ColName, RowId, PercentMatch)
GROUP BY Inserted.ValFromUser, Inserted.ColumnName, Inserted.RowNumber 
   SELECT 
      RowNumber, @firstname, 'firstname', PercentMatch, @constVal, PercentMatch * @constVal 
   FROM   
      dbo.MatchFirstName(@firstname)

1 个答案:

答案 0 :(得分:0)

为什么不能在两个不同的插入语句中执行此操作

首先插入#temp2

INSERT INTO #temp2 
            (rownumber, 
             valfromuser, 
             columnname, 
             valfromfunc, 
             funcweight, 
             percentage) 
SELECT rownumber, 
       @firstname, 
       'firstname', 
       percentmatch, 
       @constVal, 
       percentmatch * @constVal 
FROM   dbo.Matchfirstname(@firstname) 

然后将#temp2表中的分组结果插入dbo.cache

INSERT INTO dbo.cache 
            (stringsearched, 
             colname, 
             rowid, 
             percentmatch) 
SELECT valfromuser, 
       columnname, 
       rownumber, 
       Max(valfromfunc) 
FROM   #temp2  
GROUP  BY valfromuser, 
          columnname, 
          rownumber