目标:
答案 0 :(得分:1)
代码:
DECLARE @username VARCHAR(50) = '$(username)';
DECLARE @password VARCHAR(50) = '$(password)';
DECLARE @schema VARCHAR(50) = 'xxx';
DECLARE @query NVARCHAR(MAX) = '
IF NOT EXISTS(SELECT * FROM sys.database_principals WHERE NAME = ' + CHAR(39) + @username + CHAR(39) + ')
BEGIN
CREATE USER ' + @username + ' WITH PASSWORD = ' + CHAR(39) + @password + CHAR(39) + ';
ALTER USER ' + @username + ' WITH DEFAULT_SCHEMA = ' + @schema + ';
END
--ALTER ROLE db_datareader ADD MEMBER @username;
--ALTER ROLE db_datawriter ADD MEMBER @username;
GRANT SELECT ON SCHEMA::' + @schema + ' TO ' + @username + ';
GRANT INSERT ON SCHEMA::' + @schema + ' TO ' + @username + ';
GRANT UPDATE ON SCHEMA::' + @schema + ' TO ' + @username + ';
GRANT DELETE ON SCHEMA::' + @schema + ' TO ' + @username + ';
GRANT EXECUTE ON SCHEMA::' + @schema + ' TO ' + @username + ';
';
EXECUTE (@query);
Install-module -Name SqlServer -Scope CurrentUser
代码:
$passwordAdminSecure = (Get-AzureKeyVaultSecret -VaultName $keyVaultName -Name $adminSecretName).SecretValue
$passwordAdminPlain = (New-Object PSCredential "user",$passwordAdminSecure).GetNetworkCredential().Password
$dbConnectionString = "Server=tcp:$serverName.database.windows.net,1433;Initial Catalog=$dbName;Persist Security Info=False;User ID=$username;Password=$passwordAdminPlain;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
$script = Get-ChildItem -Path $PSScriptRoot -Include scriptname.sql -Recurse
$userToCreate = 'xxx'
$passwordUserSecure = (Get-AzureKeyVaultSecret -VaultName $keyVaultName -Name $userSecretName).SecretValue
$passwordUserPlain = (New-Object PSCredential "user",$passwordUserSecure).GetNetworkCredential().Password
Invoke-Sqlcmd -InputFile $script -ConnectionString $dbConnectionString -Variable username=$userToCreate, password=$passwordUserPlain -Verbose
Write-Host "Added user $userToCreate!"
代码:
SELECT DISTINCT
pr.principal_id,
pr.name,
pr.type_desc,
pr.authentication_type_desc,
pe.state_desc,
pe.permission_name
FROM sys.database_principals AS pr
JOIN sys.database_permissions AS pe
ON pe.grantee_principal_id = pr.principal_id;
答案 1 :(得分:1)
我反复遇到使用正确的参数表示法的麻烦。
您正在混合使用SQLCMD变量和TSQL变量。这很棘手。
从PowerShell编写SQL时,我发现最好让Powershell构建最终查询。像这样:
$username = "joe"
$password = "23948230948"
$schema = "dbo"
$sql = @"
IF NOT EXISTS(SELECT * FROM sys.database_principals WHERE NAME = '$username')
BEGIN
CREATE USER $username WITH PASSWORD = '$password';
ALTER USER $username WITH DEFAULT_SCHEMA = $schema;
END
GRANT SELECT ON SCHEMA::$schema TO $username;
GRANT INSERT ON SCHEMA::$schema TO $username;
GRANT UPDATE ON SCHEMA::$schema TO $username;
GRANT DELETE ON SCHEMA::$schema TO $username;
GRANT EXECUTE ON SCHEMA::$schema TO $username;
"@
invoke-sqlcmd $sql