SELECT OBJECT_DEFINITION(object_id)FROM sys.objects仅为Tables返回NULL

时间:2014-02-10 00:52:04

标签: stored-procedures sql-server-2008-r2 sqlcmd database-permissions

使用以下sp我计划将对象定义导出到文本文件,然后将它们导入SVN。 sp适用于存储过程和视图。但是,当用于用户表时,它会为每个表返回一个正确命名的文件,但内容只是字符串'NULL'。

我试图以sql用户身份执行此操作的用户。我运行了以下内容:

USE [master]
GO
GRANT VIEW ANY Definition TO bob

这似乎没有任何区别。我还尝试了在特定数据库中运行的备用语法。

USE [xxxx]
GO
GRANT VIEW Definition TO bob

我在这里失去了什么许可?还是代码问题?数据库服务器是MS SQL 2008R2 SP2

USE [xxxx]
GO
/****** Object:  StoredProcedure [dbo].[sp_Export_Objects_to_Files]    Script Date: 02/10/2014 10:52:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------
-- Author: xxxx
-- What: Exports objects to individual text files 
-- Why: Useful for importing to version control
-- Notes: The user running the SQL server instance will 
--      require access to the output path
-----------------------------------------------------------
/*************************************
TYPE    type_desc
AF  AGGREGATE_FUNCTION
C   CHECK_CONSTRAINT
D   DEFAULT_CONSTRAINT
F   FOREIGN_KEY_CONSTRAINT
FN  SQL_SCALAR_FUNCTION
FS  CLR_SCALAR_FUNCTION
IF  SQL_INLINE_TABLE_VALUED_FUNCTION
IT  INTERNAL_TABLE
P   SQL_STORED_PROCEDURE
PC  CLR_STORED_PROCEDURE
PK  PRIMARY_KEY_CONSTRAINT
S   SYSTEM_TABLE
SQ  SERVICE_QUEUE
TF  SQL_TABLE_VALUED_FUNCTION
TR  SQL_TRIGGER
U   USER_TABLE
UQ  UNIQUE_CONSTRAINT
V   VIEW
X   EXTENDED_STORED_PROCEDURE
****************************************/

ALTER PROCEDURE [dbo].[sp_Export_Objects_to_Files]
    @obj_type   varchar(2),
    @server     varchar(100),
    @user       varchar(100),
    @pass       varchar(100),
    @db         varchar(100),
    @path       varchar(100)
AS
BEGIN

    IF RIGHT(@path, 1) <> '\'
    BEGIN
        SET @path = @path + '\'
    END

    declare @obj_name varchar(1000)
    DECLARE @cmd varchar(4000)
    DECLARE @sql varchar(1000)

    IF OBJECT_ID('tempdb..#sptemp') IS NOT NULL DROP TABLE #sptemp

    CREATE TABLE #sptemp
    (
        obj_name varchar(1000)
    )


    INSERT INTO #sptemp (obj_name)
    SELECT OBJECT_NAME(object_id)
    FROM sys.objects
    WHERE type = @obj_type

    --select * from #sptemp

    DECLARE my_cursor CURSOR FOR  
    SELECT  obj_name
    FROM    #sptemp
    ORDER BY obj_name

    OPEN my_cursor  
    FETCH NEXT FROM my_cursor INTO @obj_name

    WHILE @@FETCH_STATUS = 0  
    BEGIN
        SET @sql = 'SET NOCOUNT ON;SELECT OBJECT_DEFINITION(object_id) FROM sys.objects WHERE type='''+ @obj_type + ''' AND name='''  + @obj_name + ''''
        SET @cmd = 'sqlcmd -S tcp:' + @server + ' -U ' + @user + ' -P ' + @pass + ' -d ' + @db + ' -y 0 -Q "' + @sql + '" -o ' + @path + @obj_name + '.sql'
        PRINT @cmd
        EXEC master..xp_cmdshell @cmd

        FETCH NEXT FROM my_cursor INTO @obj_name
    END

    close my_cursor
    deallocate my_cursor
END -- end of sp

1 个答案:

答案 0 :(得分:-1)

我被告知OBJECT_DEFINITION()对表不起作用