April 25, 2012

sp_grantdbaccess (Transact-SQL MetaData) Definition

Please note: that the following source code is provided and copyrighted by Microsoft and is for educational purpose only.
The meta data is from an SQL 2012 Server.

I have posted alot more, find the whole list here.

Goto Definition or MetaData

Definition:

sys.sp_grantdbaccess(nvarchar @loginame)

MetaData:

 create procedure sys.sp_grantdbaccess  
@loginame sysname,
@name_in_db sysname = NULL OUT
as
-- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
set nocount on
declare @ret int, -- return value of sp call
@sid varbinary(85),
@iswin bit,
@isgrp bit,
@stmtU nvarchar(4000),
@stmtS nvarchar(4000)

if @name_in_db is null
select @name_in_db = @loginame

-- CHECK PERMISSIONS (Shiloh Check) --
if (not is_member('db_accessadmin') = 1) and
(not is_member('db_owner') = 1)
begin
dbcc auditevent (109, 1, 0, @loginame, @name_in_db, NULL, NULL, NULL, NULL, NULL)
raiserror(15247,-1,-1)
return (1)
end

-- DISALLOW USER TRANSACTION --
set implicit_transactions off
IF (@@trancount > 0)
begin
raiserror(15002,-1,-1,'sys.sp_grantdbaccess')
return (1)
end

exec @ret = sys.sp_validname @name_in_db
if @ret <> 0
return(1)

-- IS IT A WINDOWS ACCOUNT?
select @iswin = case when (charindex('\', @loginame) <> 0) then 1 else 0 end
select @isgrp = 0

-- IS IT A WINDOWS GROUP?
if @iswin = 1
begin
select @sid = get_sid('\G'+@loginame) -- nt group?
if @sid is not null
select @isgrp = 1 -- nt group
end

-- Form Create User statement
select @stmtU = 'CREATE USER '
select @stmtU = @stmtU + quotename(@name_in_db, ']')
select @stmtU = @stmtU + ' FOR LOGIN '
select @stmtU = @stmtU + quotename(@loginame, ']')
if @isgrp = 0
begin
select @stmtU = @stmtU + ' WITH DEFAULT_SCHEMA = '
select @stmtU = @stmtU + quotename(@name_in_db, ']')
end

-- Form Create Schema statement
select @stmtS = 'CREATE SCHEMA '
select @stmtS = @stmtS + quotename(@name_in_db, ']')
select @stmtS = @stmtS + ' AUTHORIZATION '
select @stmtS = @stmtS + quotename(@name_in_db, ']')

BEGIN TRANSACTION

-- create the owner
exec (@stmtU)
if @@error <> 0
begin
ROLLBACK TRANSACTION
return (1)
end

-- create the Schema if one does not already exist with the same name and owner
declare @schema_uid int
declare @owner_uid int
select @owner_uid = principal_id from sys.database_principals where name = @name_in_db
select @schema_uid = principal_id from sys.schemas where name = @name_in_db
if (@schema_uid is null or -- there is no schema since if there is one, it will have an owner
@schema_uid <> @owner_uid) -- for error message
begin
exec (@stmtS)
if @@error <> 0
begin
ROLLBACK TRANSACTION
return (1)
end
end

COMMIT TRANSACTION

-- RETURN SUCCESS STATUS --
return (0) -- sp_grantdbaccess

No comments:

Post a Comment

Total Pageviews