如何确定MS SQL Server 2005中表值变量的内部名称

时间:2020-03-06 14:22:59  来源:igfitidea点击:

临时表的名称(例如#t1)可以使用

select @TableName = [Name]
from tempdb.sys.tables 
where [Object_ID] = object_id('tempDB.dbo.#t1')

如何找到表值变量的名称,即由声明的变量

declare @t2 as table (a int)

目的是能够使用以下方法获取有关表的元信息:

select @Headers = dbo.Concatenate('[' + c.[Name] + ']')  
from  sys.all_columns c
    inner join sys.tables t
        on c.object_id = t.object_id
where t.name = @TableName

尽管对于临时表,我们必须查找" tempdb.sys.tables"而不是" sys.tables"。我们在哪里寻找表格值变量?

现在我意识到我无法做我想做的事,这是编写一个通用函数来将表值变量格式化为html表。首先,在sql server 2005中,我们不能传递表值参数:

http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters

此外,在sql server 2008中,必须对参数进行强类型化,因此我们将始终知道列的数量和类型。

解决方案

我不相信我们可以,因为表变量是在内存中而不是在tempdb中创建的。

从在线书籍:

表变量的行为类似于局部变量。它具有定义明确的范围,该范围是在其中声明它的函数,存储过程或者批处理。

鉴于此,我们不必在运行时查找此值,因为我们必须在设计时知道它。

关于将任意列表/数组传递到SQL Server 2005函数或者sproc的主题,
我知道的最简单的方法是使用XML变量。如果需要,该XML变量可以是与XML架构相关联的强类型XML类型。

给定一个以XML形式传递到过程/函数的列表,我们可以通过"切碎"将该列表提取到表变量或者临时表中。
"切碎" XML意味着朝相反的方向转换-从XML到行集。 (FOR XML子句导致将行集转换为XML。)

在用户定义表功能中

CREATE FUNCTION [dbo].[udtShredXmlInputBondIdList]  
( 
-- Add the parameters for the function here
@xmlInputBondIdList xml
)
RETURNS 
@tblResults TABLE 
(
-- Add the column definitions for the TABLE variable here
    BondId int 
)
AS
BEGIN
-- Should add a schema validation for @xmlInputIssuerIdList here
--Place validation here
-- Fill the table variable with the rows for your result set
INSERT @tblResults
SELECT  
nref.value('.', 'int') as BondId
FROM
@xmlInputBondIdList.nodes('//BondID') as R(nref)
RETURN 
END

如果@xmlInputBondIdList是预期结构的XML片段,如下面所示,则按以下方式调用

DECLARE @xmlInputBondIdList xml
SET @xmlInputBondIdList =
'<XmlInputBondIdList>

<BondID>8681</BondID>

<BondID>8680</BondID>

<BondID>8684</BondID>

</XmlInputBondIdList>
'

SELECT * 
FROM [CorporateBond].[dbo].[udtShredXmlInputBondIdList] 
     (@xmlInputBondIdList)

结果将是行集

BondId

8681

8680

8684

可以在http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=678284&SiteID=1中找到其他几个示例。