从永久 table 行动态创建本地临时 table 列

Dynamically create local temp table columns from permanent table rows

背景: 我为第三方网络平台编写自定义 SQL 报告——多个数据库,其中大部分是 SQL Server 2008 R2 或 2012 -- 我已经 运行 遇到这样一种情况,即我的脚本的不同部分没有维护临时 table。我无法确定是否只是范围不同,或者这些部分是否使用单独的连接。无论如何,这对我来说是个大问题,因为这意味着必须从头开始多次重新创建临时 tables,或者在我不想这样做的时候不得不创建永久性 tables。

为了简化事情,我编写了一个存储过程,它获取临时 table(或任何 table,真的)的内容,旋转它,并将列作为行存储在永久table。这是永久的table:

CREATE TABLE [dbo].[CustomTempRows] (
[who] [varchar](25) NOT NULL -- A session variable from the web server
,[dtdate] [datetime] NOT NULL -- The date the row was entered
,[stable] [varchar](100) NOT NULL -- The name of the source table
,[scolumn] [varchar](100) NOT NULL -- The name of the source column
,[irow] [int] NOT NULL -- The row number from the source table
,[icolumn] [int] NOT NULL -- The column number from the source table
,[itype] [int] NOT NULL -- Whether or not the column is a string, date, or number
,[dvalue] [numeric](24, 8) NULL -- The value from the source table if it's a number.
,[svalue] [nvarchar](max) NULL -- The value from the source table if it's a string.
,[dtvalue] [datetime] NULL -- The value from the source table if it's a date.
)  

该过程获取临时文件 table 中每一行的每一列,并将其作为一行插入到 CustomTempRows table 中。它要求 temp table 有一个名为 TID 的标识列,以确定进入 irow 的行号。为简单起见,它将值转换为 nvarchar、数字或日期时间——我相信在 99% 的情况下这应该没问题。作为参考,这里是程序:

create procedure Custom_Table_Columns_to_Rows (@who varchar(max), @dtdate datetime, @stablename varchar(max), @breverse int)
as
BEGIN
/* NOTES

1. Temp table MUST have an identity column called TID
2. The procedure strips out timestamp and sysname columns

*/

declare @temptable varchar(100)
set @temptable = '##' + convert(varchar,@@SPID) 

if @breverse = 0 /* This parameter indicates that we are inserting to the custom table 
                rather than selecting.  Not sure if selecting is actually possible
                in stored procedure */
BEGIN

/* Clean up the custom table */
delete customtemprows where (who = @who and stable = @stablename) or datediff(mi,dtdate,getdate() )>60

/* Dynamic SQL to create a global temp table and copy the user's temp table into it */
exec('if OBJECT_ID(''tempdb..' + @temptable + ''') is not null drop table ' + @temptable + ';

select * into ' + @temptable + ' from ' + @stablename )

/* Insert into customtemprows for the row and column numbers, as well as the column names and data types
(which are limited to nvarchar, numeric, and datetime -- everything is converted to one of these) 
The data columns are left blank for the moment. */
exec('
insert customtemprows (who, dtdate, stable, scolumn, irow, icolumn, itype)
select 5555
, getdate()
, ''' + @stablename + '''
, c.name
, te.tid
, c.column_id
, itype = case when t.name like ''%char%'' or t.name like ''%name%'' then 1
when t.name like (''%date%'') then 2
else 3 end

from tempdb.sys.columns c
inner join sys.types t on c.system_type_id = t.system_type_id
cross join ' + @temptable + ' te

where 
object_id = object_id(''tempdb..' + @temptable + ''')
and t.name not in (''sysname'', ''timestamp'')
and c.name<>''tid''
order by te.tid, c.column_id')

/* Create variables to use when running the loop */
declare @cols as table (icolumn int, scolumn varchar(100), itype int)
insert @cols
select distinct icolumn, scolumn, itype from customtemprows where who=@who and stable = @stablename and scolumn not in ('tid') order by icolumn

declare @icolumn int, @scolumn varchar(100), @itype int

select top 1 @icolumn = icolumn, @scolumn = scolumn, @itype = itype from @cols order by icolumn

/* Loop through as long as there are columns */
while exists (select * from @cols) 
BEGIN

/* If this column is a string, put it into the svalue column */
exec('update r
set svalue = t.' + @scolumn + '
FROM 
  customtemprows r
  inner join 
 (SELECT tid, ' + @scolumn + '
   FROM ' + @temptable + ') t on r.irow=t.tid
where
r.itype = 1
and r.icolumn = ' + @icolumn + '
and r.who = ''' + @who + ''' 
and r.stable = ''' + @stablename+ '''' ) 

/* If this column is a date, put it into the dtvalue column */
exec('update r
set dtvalue = t.' + @scolumn + '
FROM 
customtemprows r
  inner join 
     (SELECT tid, ' + @scolumn + '
   FROM ' + @temptable + ') t on r.irow=t.tid
where
r.itype = 2
and r.icolumn = ' + @icolumn + '
and r.who = ''' + @who + ''' 
and r.stable = ''' + @stablename+ '''' ) 

/* If this column is a number, put it into the dvalue column */
exec('update r
set dvalue = convert(numeric(24,10),t.' + @scolumn + ')
FROM 
  customtemprows r
  inner join 
     (SELECT tid, ' + @scolumn + '
   FROM ' + @temptable + ') t on r.irow=t.tid
where
r.itype = 3
and r.icolumn = ' + @icolumn + '
and r.who = ''' + @who + ''' 
and r.stable = ''' + @stablename+ '''' ) 

delete @cols where icolumn = @icolumn

select top 1 @icolumn = icolumn, @scolumn = scolumn, @itype = itype from @cols order by icolumn

END /* Loop */

/* Return the inserted values.  For troubleshooting */
select * from customtemprows where who = @who and stable = @stablename order by icolumn, irow
END /* @breverse = 0 */

END

我的问题 正在找出将数据从 CustomTempRows 中取出并返回到临时 table 以用于其他部分的最佳方法我的报告。我已经写了一份可以完成这项工作的声明,但我对此并不满意。我将解释原因,但首先,这是查询:

declare @who varchar(100), @stablename varchar(100), @temptable varchar(100)

/* Set user variables */
set @who = '5555' /* Usually Session ID */
set @stablename = '#temp' /* The temp table you started with */
set @temptable = '##global' /* The name of the global temp table to create */

/* Drop the global temp table if it exists */
exec('if OBJECT_ID(''tempdb..' + @temptable + ''') is not null drop table ' + @temptable )

declare @columns varchar(max)
declare @rows as table (irow int, icolumn int, scolumn varchar(100), itype int, svalue nvarchar(max))
declare @irow int, @icolumn int, @scolumn varchar(100), @itype int, @svalue nvarchar(max), @convert varchar(50)
declare @sql varchar(max)

/* Create a list of columns to include in the temp table */
set @columns = '';
select @columns = @columns + ', ' + scolumn + ' ' + case r.itype when 1 then 'nvarchar(max)' when 2 then 'datetime' else 'numeric(24,10)' end + ' NULL'
FROM (select distinct icolumn, scolumn, itype from customtemprows 
where stable=@stablename and who = @who) r

select @columns = STUFF(@columns, 1, 2, '')

/* Create the global temp table and populate the TID column */
exec('create table ' + @temptable + '  (tid int, ' + @columns + ');

insert ' + @temptable + ' (tid)
select distinct irow from customtemprows where stable=''' + @stablename + ''' and who = ''' + @who + '''')

/* create data for the loop */
insert @rows
select irow, icolumn, scolumn, itype

/* Can't combine data types; convert everything to string */
, svalue = coalesce(svalue, convert(nvarchar,dvalue), convert(nvarchar,dtvalue)) 

from customtemprows where stable = @stablename and who = @who
order by icolumn, irow

select top 1 @irow = irow, @icolumn = icolumn, @scolumn = scolumn, @itype = itype, @svalue = svalue
/* For converting the string back to its previous data type */
, @convert = case when itype = 1 then 'convert(nvarchar(max),svalue)' 
    when itype = 2 then 'convert(datetime,svalue)'
    else 'convert(numeric(24,10),svalue)' end
     from @rows order by icolumn, irow

/* As long as there are rows */
while exists (select * from @rows)

BEGIN
set @sql = ''

/* Update the temp table one column at a time with data from the table variable */
select @sql = 'update t
set ' + @scolumn + ' = ' + @convert + '
from 
' + @temptable + ' t
inner join (
select irow, icolumn, scolumn, itype, svalue = coalesce(svalue,    convert(nvarchar,dvalue), convert(nvarchar,dtvalue)) 
from customtemprows where stable=''' + @stablename + ''' and who = ''' + @who + ''') r
on r.irow=t.tid and r.icolumn = ' + convert(varchar,@icolumn) 


exec(@sql)

delete @rows where icolumn = @icolumn

select top 1 @irow = irow, @icolumn = icolumn, @scolumn = scolumn, @itype = itype, @svalue = svalue
, @convert = case when itype = 1 then 'convert(nvarchar(max),svalue)' 
    when itype = 2 then 'convert(datetime,svalue)'
    else 'convert(numeric(24,10),svalue)' end
     from @rows order by icolumn, irow 


END /* Loop */

select * from ##global

这不是最优雅的解决方案,我想最终用基于集合的东西替换 while 循环,但这些是更大的问题:

  1. 我想将此(或至少其中的大部分)移动到一个存储过程中,以便我可以与同事共享它,而不必在每次使用它时都重新生成那么大的代码块。
  2. 我想将最终结果放入本地而不是全局临时文件 table。

不过,为了做到这一点,我必须在调用过程之前定义温度 table(我正在开发的平台的限制)。因为我正在使用动态 SQL 来创建 table,所以我不知道如何在我需要使用它的同一范围内创建 table。

我也宁愿使用序号来命名全局临时文件table,以防止两个用户同时访问报表时发生冲突。但同样,如果我这样做,我的报告代码的其余部分将不知道 table.

的名称

我的问题:是否有可能根据 CustomTempRows 中的数据定义本地温度 table,这将在我的报告范围内可用,然后根据我的长查询使用存储过程填充 table?

感谢您看完我的 post,并感谢您提出任何建议。不胜感激。

创建一个包含 1 列的临时 table,然后动态地 运行 动态 SQL 以向临时 table 添加其他字段。

DECLARE @SQL varchar(max)

CREATE TABLE #tmp(Id int)

SET @SQL = 'ALTER TABLE #tmp ADD Column1 varchar(20)'
EXEC(@SQL)