如何在SQL脚本中创建TYPE TABLE?

时间:2014-01-15 01:39:31

标签: sql sql-server

我正在尝试创建一个表格类型,我将其作为参数传递给过程。但是,一旦我开始收到错误,一旦声称该类型不存在,或者由于程序需要它而无法删除它。这是我到目前为止所得到的:

- 创建类型:

IF TYPE_ID('usr.NameList') IS NOT NULL DROP TYPE usr.NameList; -- Cannot drop type 'usr.NameList' because it is being referenced by object 'JWBestMatch'. There may be other objects that reference this type.
CREATE TYPE usr.NameList AS TABLE ([name] VARCHAR(MAX) NOT NULL);

-- delete the procedure if it already exists:
IF OBJECT_ID('TEMPDB..#JWBestMatch') IS NOT NULL DROP PROCEDURE #JWBestMatch;

-- create the procedure
GO
CREATE PROCEDURE #JWBestMatch -- Cannot find data type usr.NameList
    @name NVARCHAR(MAX),
    @referenceTable usr.NameList READONLY,
    @bestMatch NVARCHAR(MAX) OUTPUT
AS
BEGIN
    RETURN;
END;
GO

那么你如何创建一个类型呢?在我读过的文档中,他们只是简单地告诉你如何创建它,而不是如何实际创建一个在运行一次之后不会失败的脚本。我在这里缺少什么?

2 个答案:

答案 0 :(得分:1)

我认为这就是你要做的事情:

IF OBJECT_ID('JWBestMatch') IS NOT NULL DROP PROCEDURE JWBestMatch;
GO

IF TYPE_ID('usr.NameList') IS NOT NULL DROP TYPE usr.NameList;
GO

CREATE TYPE usr.NameList AS TABLE ([name] VARCHAR(MAX) NOT NULL);


GO

CREATE PROCEDURE JWBestMatch
    @name NVARCHAR(MAX),
    @referenceTable usr.NameList READONLY,
    @bestMatch NVARCHAR(MAX) OUTPUT
AS
BEGIN
    RETURN;
END;
GO

答案 1 :(得分:0)

不使用临时数据库进行处理而不是每次都删除类型:

IF TYPE_ID('usr.NameList') IS NULL CREATE TYPE usr.NameList AS TABLE ([name] VARCHAR(MAX) NOT NULL);

-- delete the procedure if it already exists:
IF OBJECT_ID('usr.JWBestMatch') IS NOT NULL DROP PROCEDURE usr.JWBestMatch;

-- create the procedure
GO
CREATE PROCEDURE usr.JWBestMatch
    @name NVARCHAR(MAX),
    @referenceTable usr.NameList READONLY,
    @bestMatch NVARCHAR(MAX) OUTPUT
AS
BEGIN
    RETURN;
END;
GO