[推荐] (SqlServer)分离所有用户数据库

核心提示:需求:需要生成下面的序列号,前半部分是yyyymmdd格式的年月日时间数字,后半部分则是每天都从1顺序增长的数字,位数要固定,中间不足的补0

USE MASTER GO IF EXISTS(SELECT * FROM dbo.sysdatabases WHERE
name=’my_test_database’) DROP DATABASE [my_test_database] GO
CREATE DATABASE [my_test_database] GO USE [my_test_database] GO
CREATE TABLE [my_table] ([my_id] VARCHAR(16)) GO –存储过程开始 :
CREATE PROCEDURE get_new_id @NEW_ID VARCHAR(16) OUTPUT AS BEGIN
DECLARE @DATE DATETIME DECLARE @YYYY VARCHAR(4) DECLARE @MM VARCHAR(2)
DECLARE @DD VARCHAR(2) –保存取得的当前时间 : SET @DATE = GETDATE() SET
@YYYY = DATEPART(yyyy, @DATE) SET @MM = DATEPART(mm, @DATE) SET @DD =
DATEPART(dd, @DATE) –位数不够的前面补0 SET @YYYY = REPLICATE(‘0’, 4 –
LEN(@YYYY)) + @YYYY SET @MM = REPLICATE(‘0’, 2 – LEN(@MM)) + @MM SET @DD
= REPLICATE(‘0′, 2 – LEN(@DD)) + @DD –取出表中当前日期的已有的最大ID
SET @NEW_ID = NULL SELECT TOP 1 @NEW_ID = [my_id] FROM
[my_table] WHERE [my_[推荐] (SqlServer)分离所有用户数据库。id] LIKE @YYYY+@MM+@DD+’%’ ORDER BY
[my_id] DESC –如果未取出来 IF @NEW_ID IS NULL
–说明还没有当前日期的编号,则直接从1开始编号 SET @NEW_ID =
(@YYYY+@MM+@DD+’00000001′) –如果取出来了 : ELSE BEGIN DECLARE @NUM
VARCHAR(8) –取出最大的编号加上1 : SET @NUM = CONVERT(VARCHAR,
(CONVERT(INT, RIGHT(@NEW_ID, 8)) + 1))
–因为经过类型转换,丢失了高位的0,需要补上 SET @NUM = REPLICATE(‘0’, 8

[推荐](SqlServer)分离所有用户数据库

[推荐]得到一个给定用户使用了的权限脚本

需求:需要生成下面的序列号,前半部分是yyyymmdd格式的年月日时间数字,后半部分则是每天都从1顺序增长的数字,位数要固定,中间不足的补0。
在SQL Server 2000数据库中测试后通过如下代码,功能实现如下:

  • LEN(@NUM)) + @NUM –最后返回日期加编号 : SET @NEW_ID = @YYYY+@MM+@DD
  • @NUM END END GO –执行20次调用及插入数据测试 : DECLARE @N INT SET @N
    = 0 WHILE @N 20 BEGIN DECLARE @NEW_ID VARCHAR(16) EXECUTE get_new_id
    @NEW_ID OUTPUT INSERT INTO [my_table] ([my_id]) VALUES (@NEW_ID)
    SET @N = @N + 1 END SELECT * FROM [my_table] GO –输出结果

——通过知识共享树立个人品牌。

——通过知识共享树立个人品牌。

USE MASTER

在实际应用中,有时我们需要一次性分离所有用户数据库,下面给出代码,供大家参考。

得到一个给定用户使用了的权限脚本,直接上代码,自己研究。

GO

 

     SET ANSI_NULLS ON

IF EXISTS(SELECT * FROM dbo.sysdatabases WHERE name=my_test_database)

USE [master]
GO
IF EXISTS ( SELECT *
 FROM sys.objects
 WHERE [object_id] = OBJECT_ID(N'[dbo].[spDetachAllUserDatabases]’)
 AND type IN ( N’P’, N’PC’ ) ) 
 DROP PROCEDURE [dbo].[spDetachAllUserDatabases]
GO

GO
SET QUOTED_IDENTIFIER ON
GO

DROP DATABASE [my_test_database]

CREATE PROCEDURE [dbo].[spDetachAllUserDatabases]
AS 
 BEGIN
     –Declare Variables
     DECLARE @DatabaseName VARCHAR(100)
     DECLARE @MinDatabaseID INT
     DECLARE @MaxDatabaseID INT
     DECLARE @SQL VARCHAR(4000)
     –Check for temporary table and drop it if it exists
     IF OBJECT_ID(‘tempDB.dbo.#Database’) IS NOT NULL 
     DROP TABLE [#Database];

CREATE PROCEDURE [dbo].[p_user_permissions_script_get] 

— OBJECT NAME :dbo.p_user_permissions_script_get
— AUTHOR: EricHu
— DATE: 01/05/2012
— INPUT PARAMETERS:         

GO

     –Create temporary table
     CREATE TABLE #Database
     (
     ID INT IDENTITY(1, 1),
     DatabaseName VARCHAR(100)
     )
     
     –Check for existing user databases
     IF EXISTS ( SELECT name
     FROM sys.databases
     WHERE database_id > 4
     AND name NOT IN ( ‘SQLDBA’, ‘ReportServer’,
     ‘ReportServerTempDB’,
     ‘distribution’ ) ) 
     BEGIN 
         –Insert all database names into a temporary table
         INSERT INTO #Database ( DatabaseName )
         SELECT name
         FROM sys.databases
         WHERE database_id > 4
         AND name NOT IN ( ‘SQLDBA’, ‘ReportServer’,
         ‘ReportServerTempDB’,
         ‘distribution’ ) 
         
         –Set Variables for the detach database loop 
         SELECT @MinDatabaseID = MIN(ID),
         @MaxDatabaseID = MAX(ID)
         FROM #Database
        
         –Begin loop to detach databases
         WHILE @MinDatabaseID <= @MaxDatabaseID
         BEGIN
         
         –Get DatabaseName
         SELECT @DatabaseName = DatabaseName
         FROM #Database
         WHERE ID = @MinDatabaseID
         
         –Build Detach Database Command
         SET @SQL = ‘EXEC sp_detach_db ‘ + ”” + @DatabaseName
         + ”” + ‘;’

    @userName VARCHAR(500)

— OUTPUT PARAMETERS: none
— DEPENDENCIES: none
— DESCRIPTION: Used to script out permissions for a given user

CREATE DATABASE [my_test_database]

         –Try Catch block to execute SQL and handle errors  
         BEGIN TRY

— MODIFICATION HISTORY: 

AS

SET NOCOUNT ON

DECLARE @DatabaseUserName [SYSNAME];

SET @DatabaseUserName = @userName;

DECLARE @errStatement   VARCHAR(1000),
        @msgStatement   VARCHAR(1000),
        @DatabaseUserID SMALLINT,
        @ServerUserName SYSNAME,
        @RoleName       VARCHAR(1000),
        @ObjectID       INT,
        @ObjectName     VARCHAR(1000),
        @StateDesc       VARCHAR(1000),
        @permissionName VARCHAR(1000)
        
        
      

SELECT @DatabaseUserID = su.[uid],
       @ServerUserName = sl.[loginname]
FROM   dbo.[sysusers] su
       INNER JOIN [master].dbo.[syslogins] sl
         ON su.[sid] = sl.[sid]
WHERE  su.[name] = @DatabaseUserName

IF @DatabaseUserID IS NULL
  BEGIN
      SET @errStatement = ‘User ‘ + @DatabaseUserName + ‘ does not exist in ‘ + DB_NAME() 
                        + CHAR(13) + ‘Please provide the name of a current user in ‘ + DB_NAME() 
                        + ‘ you wish to script.’

      RAISERROR(@errStatement,
                16,
                1)
  END
ELSE
  BEGIN
      SET @msgStatement = ‘–Security creation script for user ‘ + @ServerUserName + CHAR(13) 
                        + ‘–Created At: ‘ + CONVERT(VARCHAR, GETDATE(), 100) 
                        + REPLACE(CONVERT(VARCHAR, GETDATE(), 108), ‘:’, ”) + CHAR(13) 
                        + ‘–Created By: ‘ + SUSER_NAME() + CHAR(13) + ‘–Add User To Database’ 
                        + CHAR(13) + ‘USE [‘ + DB_NAME() + ‘]’ + CHAR(13) 
                        + ‘EXEC [sp_grantdbaccess]’ + CHAR(13) + CHAR(9) 
                        + ‘@loginame = ”’ + @ServerUserName + ”’,’ + CHAR(13) + CHAR(9) 
                        + ‘@name_in_db = ”’ + @DatabaseUserName + ”” + ‘;’+ CHAR(13) + ‘GO’ 
                        + CHAR(13) + ‘–Add User To Roles’

      PRINT @msgStatement

      DECLARE _sysusers CURSOR LOCAL FORWARD_ONLY READ_ONLY FOR
        SELECT [name]
        FROM   [dbo].[sysusers]
        WHERE  [uid] IN (SELECT [groupuid]
                         FROM   [dbo].[sysmembers]
                         WHERE  [memberuid] = @DatabaseUserID)

      OPEN _sysusers

      FETCH NEXT FROM _sysusers INTO @RoleName

      WHILE @@FETCH_STATUS = 0
        BEGIN
            SET @msgStatement = ‘EXEC [sp_addrolemember]’ + CHAR(13) + CHAR(9) + ‘@rolename = ”’ 
                              + @RoleName + ”’,’ + CHAR(13) + CHAR(9) + ‘@membername = ”’ 
                              + @DatabaseUserName + ””  + ‘;’ ;

            PRINT @msgStatement

            FETCH NEXT FROM _sysusers INTO @RoleName
        END
        
        
        CLOSE _sysusers;
        
        DEALLOCATE _sysusers;
        
       –Database level perms;
       
       PRINT ‘–Set Database level Permissions’;
       DECLARE _databaselevelperms CURSOR LOCAL FORWARD_ONLY READ_ONLY FOR      
        SELECT 
             sdp.state_desc,
             sdp.permission_name
        FROM 
            sys.database_permissions sdp WITH(NOLOCK)
            
            JOIN sysusers  su WITH(NOLOCK)
                ON su.uid = sdp.grantee_principal_id
                
        WHERE 
            su.name = @userName
            AND sdp.class_desc = ‘DATABASE’;
    

      OPEN _databaselevelperms;
      
      FETCH NEXT FROM _databaselevelperms INTO @StateDesc, @PermissionName;
      
      WHILE @@FETCH_STATUS = 0 
      BEGIN 
      
        PRINT @StateDesc  + CHAR(13) + CHAR(9) + @PermissionName  + CHAR(13) + CHAR(9) 
              + ‘TO ‘ + @userName + ‘;’;
        
        FETCH NEXT FROM _databaselevelperms INTO @StateDesc, @PermissionName
        
      END
      
      CLOSE _databaselevelperms;

      DEALLOCATE _databaselevelperms;

      SET @msgStatement = ‘GO’ + CHAR(13) + ‘–Set Object Specific Permissions’

      PRINT @msgStatement;

      DECLARE _sysobjects CURSOR LOCAL FORWARD_ONLY READ_ONLY FOR
        SELECT DISTINCT( [www.9778.com,sysobjects].[id] ),
                       ‘[‘ + USER_NAME([sysobjects].[uid]) + ‘].[‘ + [sysobjects].[name] + ‘]’
        FROM   [dbo].[sysprotects]
               INNER JOIN [dbo].[sysobjects]
                 ON [sysprotects].[id] = [sysobjects].[id]
        WHERE  [sysprotects].[uid] = @DatabaseUserID;

      OPEN _sysobjects;

      FETCH NEXT FROM _sysobjects INTO @ObjectID, @ObjectName;

      WHILE @@FETCH_STATUS = 0
        BEGIN
            SET @msgStatement = ”;

            IF EXISTS(SELECT 1
                      FROM   [dbo].[sysprotects]
                      WHERE  [id] = @ObjectID
                             AND [uid] = @DatabaseUserID
                             AND [action] = 193
                             AND [protecttype] = 205)
              SET @msgStatement = @msgStatement + ‘SELECT,’;

            IF EXISTS(SELECT 1
                      FROM   [dbo].[sysprotects]
                      WHERE  [id] = @ObjectID
                             AND [uid] = @DatabaseUserID
                             AND [action] = 195
                             AND [protecttype] = 205)
              SET @msgStatement = @msgStatement + ‘INSERT,’;

            IF EXISTS(SELECT 1
                      FROM   [dbo].[sysprotects]
                      WHERE  [id] = @ObjectID
                             AND [uid] = @DatabaseUserID
                             AND [action] = 197
                             AND [protecttype] = 205)
              SET @msgStatement = @msgStatement + ‘UPDATE,’;

            IF EXISTS(SELECT 1
                      FROM   [dbo].[sysprotects]
                      WHERE  [id] = @ObjectID
                             AND [uid] = @DatabaseUserID
                             AND [action] = 196
                             AND [protecttype] = 205)
              SET @msgStatement = @msgStatement + ‘DELETE,’;

            IF EXISTS(SELECT 1
                      FROM   [dbo].[sysprotects]
                      WHERE  [id] = @ObjectID
                             AND [uid] = @DatabaseUserID
                             AND [action] = 224
                             AND [protecttype] = 205)
              SET @msgStatement = @msgStatement + ‘EXECUTE,’;

            IF EXISTS(SELECT 1
                      FROM   [dbo].[sysprotects]
                      WHERE  [id] = @ObjectID
                             AND [uid] = @DatabaseUserID
                             AND [action] = 26
                             AND [protecttype] = 205)
              SET @msgStatement = @msgStatement + ‘REFERENCES,’;

            IF LEN(@msgStatement) > 0
              BEGIN
                  IF RIGHT(@msgStatement, 1) = ‘,’
                    SET @msgStatement = LEFT(@msgStatement, LEN(@msgStatement) – 1);

                  SET @msgStatement = ‘GRANT’ + CHAR(13) + CHAR(9) + @msgStatement + CHAR(13) 
                                    + CHAR(9) + ‘ON ‘ + @ObjectName + CHAR(13) + CHAR(9) + ‘TO ‘ 
                                    + @DatabaseUserName + ‘;’ ;

                  PRINT @msgStatement;
              END

            SET @msgStatement = ”;

            IF EXISTS(SELECT 1
                      FROM   [dbo].[sysprotects]
                      WHERE  [id] = @ObjectID
                             AND [uid] = @DatabaseUserID
                             AND [action] = 193
                             AND [protecttype] = 206)
              SET @msgStatement = @msgStatement + ‘SELECT,’

            IF EXISTS(SELECT 1
                      FROM   [dbo].[sysprotects]
                      WHERE  [id] = @ObjectID
                             AND [uid] = @DatabaseUserID
                             AND [action] = 195
                             AND [protecttype] = 206)
              SET @msgStatement = @msgStatement + ‘INSERT,’;

            IF EXISTS(SELECT 1
                      FROM   [dbo].[sysprotects]
                      WHERE  [id] = @ObjectID
                             AND [uid] = @DatabaseUserID
                             AND [action] = 197
                             AND [protecttype] = 206)
              SET @msgStatement = @msgStatement + ‘UPDATE,’;

            IF EXISTS(SELECT 1
                      FROM   [dbo].[sysprotects]
                      WHERE  [id] = @ObjectID
                             AND [uid] = @DatabaseUserID
                             AND [action] = 196
                             AND [protecttype] = 206)
              SET @msgStatement = @msgStatement + ‘DELETE,’

            IF EXISTS(SELECT 1
                      FROM   [dbo].[sysprotects]
                      WHERE  [id] = @ObjectID
                             AND [uid] = @DatabaseUserID
                             AND [action] = 224
                             AND [protecttype] = 206)
              SET @msgStatement = @msgStatement + ‘EXECUTE,’;

            IF EXISTS(SELECT *
                      FROM   [dbo].[sysprotects]
                      WHERE  [id] = @ObjectID
                             AND [uid] = @DatabaseUserID
                             AND [action] = 26
                             AND [protecttype] = 206)
              SET @msgStatement = @msgStatement + ‘REFERENCES,’;

            IF LEN(@msgStatement) > 0
              BEGIN
                  IF RIGHT(@msgStatement, 1) = ‘,’
                    SET @msgStatement = LEFT(@msgStatement, LEN(@msgStatement) – 1)

                  SET @msgStatement = ‘DENY’ + CHAR(13) + CHAR(9) + @msgStatement + CHAR(13) 
                                    + CHAR(9) + ‘ON ‘ + @ObjectName + CHAR(13) + CHAR(9) + ‘TO ‘ 
                                    + @DatabaseUserName + ‘;’ ;

                  PRINT @msgStatement;
              END

            FETCH NEXT FROM _sysobjects INTO @ObjectID, @ObjectName;
        END

      CLOSE _sysobjects;

      DEALLOCATE _sysobjects;
      
   

      PRINT ‘GO’
  END 

SET NOCOUNT OFF

RETURN 0

      运行结果实例如下:

 EXEC [p_user_permissions_script_get] ‘dbo’

–Security creation script for user sa
–Created At: 01 13 2012  4:37PM163729
–Created By: sa
–Add User To Database
USE [DB_TEST]
EXEC [sp_grantdbaccess]
    @loginame = ‘sa’,
    @name_in_db = ‘dbo’;
GO
–Add User To Roles
EXEC [sp_addrolemember]
    @rolename = ‘db_owner’,
    @membername = ‘dbo’;
–Set Database level Permissions
GRANT
    CONNECT
    TO dbo;
GO
–Set Object Specific Permissions
GO

GO

         –Detach Database
         EXEC ( @SQL
         )
         PRINT ‘Detached ‘ + @DatabaseName
         END TRY
         BEGIN CATCH
         SELECT @DatabaseName,
         message_id,
         severity,
         [text],
         @SQL
         FROM sys.messages
         WHERE message_id = @@ERROR
         AND language_id = 1033 –British English
         END CATCH

USE [my_test_database]

         –Get the next DatabaseName ID
         SET @MinDatabaseID = @MinDatabaseID + 1
         
         –End Loop
         END
     END
 END

GO

GO

CREATE TABLE [my_table] ([my_id] VARCHAR(16))

 

GO

–存储过程开始

CREATE PROCEDURE get_new_id

@NEW_ID VARCHAR(16) OUTPUT

AS

BEGIN

DECLARE @DATE DATETIME

DECLARE @YYYY VARCHAR(4)

DECLARE @MM VARCHAR(2)

DECLARE @DD VARCHAR(2)

–保存取得的当前时间

SET @DATE = GETDATE()

SET @YYYY = DATEPART(yyyy, @DATE)

SET @MM = DATEPART(mm, @DATE)

SET @DD = DATEPART(dd, @DATE)

–位数不够的前面补0

SET @YYYY = REPLICATE(0, 4 – LEN(@YYYY)) + @YYYY

SET @MM = REPLICATE(0, 2 – LEN(@MM)) + @MM

SET @DD = REPLICATE(0, 2 – LEN(@DD)) + @DD

–取出表中当前日期的已有的最大ID

SET @NEW_ID = NULL

SELECT TOP 1 @NEW_ID = [my_id] FROM [my_table] WHERE [my_id]
LIKE @YYYY+@MM+@DD+% ORDER BY [my_id] DESC

–如果未取出来

IF @NEW_ID IS NULL

–说明还没有当前日期的编号,则直接从1开始编号

SET @NEW_ID = (@YYYY+@MM+@DD+00000001)

–如果取出来了

ELSE

BEGIN

DECLARE @NUM VARCHAR(8)

–取出最大的编号加上1

SET @NUM = CONVERT(VARCHAR, (CONVERT(INT, RIGHT(@NEW_ID, 8)) + 1))

–因为经过类型转换,丢失了高位的0,需要补上

SET @NUM = REPLICATE(0, 8 – LEN(@NUM)) + @NUM

–最后返回日期加编号

SET @NEW_ID = @YYYY+@MM+@DD + @NUM

END

END

GO

–执行20次调用及插入数据测试

DECLARE @N INT

SET @N = 0

WHILE @N 20

BEGIN

DECLARE @NEW_ID VARCHAR(16)

EXECUTE get_new_id @NEW_ID OUTPUT

INSERT INTO [my_table] ([my_id]) VALUES (@NEW_ID)

SET @N = @N + 1

END

SELECT * FROM [my_table]

GO

–输出结果

/**//*

my_id


2006092700000001

2006092700000002

2006092700000003

2006092700000004

2006092700000005

2006092700000006

2006092700000007

2006092700000008

2006092700000009

2006092700000010

2006092700000011

2006092700000012

2006092700000013

2006092700000014

2006092700000015

2006092700000016

2006092700000017

2006092700000018

2006092700000019

2006092700000020

*/

注释:原来yyyymmdd格式的日期直接这样取即可:

SELECT CONVERT(CHAR(8), GETDATE(), 112)

–输出结果:

/**//*


20060927

*/