【问题标题】:use pivot table in stored procedure在存储过程中使用数据透视表
【发布时间】:2013-07-29 13:58:17
【问题描述】:

我有一个效果很好的数据透视查询!

;with PivotData As (
Select KeyField, ColumnName, FieldValue FROM
(SELECT SomeField as KeyField, NameField As ColumnName, DataField as FieldValue
FROM Table1
UNION
SELECT SomeField, NameField, DataField
FROM Table2)
SELECT [List of Fields] FROM PivotData
PIVOT (Max(PivotData.FieldValue) for ColumnName In ([List of Fields])) As P

现在我想将该查询用作存储过程中临时表的源,但我尝试将查询结果插入临时表的语法均无效。

我可以根据结果创建一个临时表吗?如果有,怎么做?

谢谢!

莱斯利

【问题讨论】:

  • 您究竟需要 temp tbl 做什么?作为 SP 内部的中间记录集还是用 SP 结果集提供它?还是将其填充到 SP 中?
  • 我需要对返回的数据运行一系列查询,以确定是否应在数据库的表中插入一条记录。
  • 是的,我明白了。该过程中的临时表在哪里?
  • 当我启动存储过程时,我需要运行我的数据透视查询,然后运行 ​​15 个不同的查询并在满足任何条件时设置一个布尔值。在存储过程结束时,如果布尔值为 false,我不插入记录。
  • Leslie,我想知道你在临时表中填写了什么。我将假设您填写了数据透视查询的结果。所以,你必须(1)创建#temp表,(2)用数据透视填充#temp,(3-1)运行query1并据此更新#temp.myFlag,(3-2)运行query2并更新# temp.myFlag 据此,... (3-15) 运行 query15 并据此更新#temp.myFlag; (4) 插入destinationTbl (...) select ... from #temp where myFlag = 1; HTH

标签: sql-server stored-procedures pivot-table temp-tables


【解决方案1】:

请试试这个:

;with PivotData As (
Select KeyField, ColumnName, FieldValue FROM
(SELECT SomeField as KeyField, NameField As ColumnName, DataField as FieldValue
FROM Table1
UNION
SELECT SomeField, NameField, DataField
FROM Table2)
SELECT [List of Fields] into #temp FROM PivotData
PIVOT (Max(PivotData.FieldValue) for ColumnName In ([List of Fields])) As P

在这里,您不必专门为此目的声明表或表变量。

【讨论】:

  • 不要忘记在存储过程结束时删除临时表!此外,它的语法不正确。
  • @JoeFletch:什么临时表?顺便说一句,当 SP 退出时,临时 tbls 会被粉碎。
  • 我在发帖后大约 5 分钟就知道了!这不就是它通常的工作方式吗!
  • @OzrenTkalčecKrznarić,#temp,不是吗?否则下次运行存储过程时,SELECT ... INTO #temp 将失败。
  • @JoeFletch:见this
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-15
  • 1970-01-01
  • 2020-09-01
  • 2019-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多