Add users to multiple database / SQL SERVER - sql

I have to add users to multiple database in only one script
The login was created so i only need mapped the users to his respective database and give him datareader permissions.
I think that my only problem is how select and use the database because i only can assign permission for one database (step by step)
This is my code (I know that after i gotta execute)
SELECT
'USE [' + name + N']' + CHAR(13) + CHAR(10)
+ 'create user [sd-reader] for login [sd-reader]' + CHAR(13) + CHAR(10)
+ 'EXEC sp_addrolemember ''db_datareader'', ''sd-reader'''
FROM sys.databases
WHERE database_id > 7;
The databases that i need are between 8 and 12 id

Set the result to text mode and run the query
;With Results as
(
SELECT database_id as id, cast(
'USE [' + name + N']' + CHAR(13) + CHAR(10)
+ 'create user [sd-reader] for login [sd-reader]' + CHAR(13) + CHAR(10)
+ 'EXEC sp_addrolemember ''db_datareader'', ''sd-reader''' as nvarchar(max)) as qry
FROM sys.databases
where database_id = 1
Union all
SELECT database_id as id, cast (
('USE [' + name + N']' + CHAR(13) + CHAR(10)
+ 'create user [sd-reader] for login [sd-reader]' + CHAR(13) + CHAR(10)
+ 'EXEC sp_addrolemember ''db_datareader'', ''sd-reader''' + + CHAR(13) + CHAR(10) + + CHAR(10) + Results.qry ) as nvarchar(max)) as qry
FROM sys.databases join Results on (Results.id + 1 = sys.databases.database_id)
where sys.databases.database_id > 1
)
select top 1 qry from Results
order by id desc

Related

How to display the output and also save it in global temp table in ms-sql

Usually when we use select statement it displays the output, but when insert into is used,stores the result into temp table.i want to do both.Display result and store in temp table as well in dynamic sql.
IF #DisplayInSelect IS NOT NULL
SET #DisplayInSelect = ','+#DisplayInSelect
SET #SQL = 'IF EXISTS (SELECT DISTINCT a.'+#column_name+' FROM ['+#TableName+'] a where '+#FullCondition+' )'+
'SELECT DISTINCT ''Error at column: '+#Column_name+''' as [Error Records if found any are shown below],'''+ISNULL(#CustomErrorMessage,'ERROR')+''''+ISNULL(#DisplayInSELECT,'')+', a.'+#column_name+',* FROM ['+#TableName+'] a where '+#FullCondition+'
INSERT INTO ##error_check(SELECT DISTINCT ''Error at column: '+#Column_name+''' as [Error Records if found any are shown below],'''+ISNULL(#CustomErrorMessage,'ERROR')+''''+ISNULL(#DisplayInSELECT,'')+', a.'+#column_name+', *FROM ['+#TableName+'] a where '+#FullCondition+');
PRINT('IQR1 sql is'+#SQL)
EXEC(#SQL)
END
You have to use insert into table along with Exec. Try like this,
IF #DisplayInSelect IS NOT NULL
SET #DisplayInSelect = ',' + #DisplayInSelect
SET #SQL = 'IF EXISTS (SELECT DISTINCT a.' + #column_name + ' FROM [' + #TableName + '] a where ' + #FullCondition + ' )' + 'SELECT DISTINCT ''Error at column: ' + #Column_name + ''' as [Error Records if found any are shown below],''' + ISNULL(#CustomErrorMessage, 'ERROR') + '''' + ISNULL(#DisplayInSELECT, '') + ', a.' + #column_name + ',* FROM [' + #TableName + '] a where ' + #FullCondition + '
SELECT DISTINCT ''Error at column: ' + #Column_name + ''' as [Error Records if found any are shown below],''' + ISNULL(#CustomErrorMessage, 'ERROR') + '''' + ISNULL(#DisplayInSELECT, '') + ', a.' + #column_name + ', *FROM [' + #TableName + '] a where ' + #FullCondition + ';'
--To Save
INSERT INTO ##error_check
EXEC (#SQL)
PRINT (' IQR1 sql IS ' + #SQL)
--To Display
EXEC (#SQL)

sp_MSforeachtable Abuse (Modification needed)

Recently someone hacked into our database using sp_MSforeachtable, so multiline query if im right.
Now my question is how i can modify sys.sp_MSforeachtable, he is using #command1 and other commands to execute a query in order to drop our tables.
XXXX=Censored db name
(Somehow also spaces in front of the USE)
USE XXXX;
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all";
EXEC sp_MSforeachtable #command1 = "DROP TABLE ?"
Then my SQL Profiler shows:
select #mscat = ltrim(str(convert(int, 0x0002)))
exec(N'declare hCForEachTable cursor global for select ''['' + REPLACE(schema_name(syso.schema_id), N'']'', N'']]'') + '']'' + ''.'' + ''['' + REPLACE(object_name(o.id), N'']'', N'']]'') + '']'' from dbo.sysobjects o join sys.all_objects syso on o.id = syso.object_id '
+ N' where OBJECTPROPERTY(o.id, N''IsUserTable'') = 1 ' + N' and o.category & ' + #mscat + N' = 0 '
+ #whereand)
declare hCForEachTable cursor global for select '[' + REPLACE(schema_name(syso.schema_id), N']', N']]') + ']' + '.' + '[' + REPLACE(object_name(o.id), N']', N']]') + ']' from dbo.sysobjects o join sys.all_objects syso on o.id = syso.object_id where OBJECTPROPERTY(o.id, N'IsUserTable') = 1 and o.category & 2 = 0
exec #retval = sys.sp_MSforeach_worker #command1, #replacechar, #command2, #command3, 0
create table #qtemp ( /* Temp command storage */
qnum int NOT NULL,
qchar nvarchar(2000) COLLATE database_default NULL
)
Could anyone let me know how to secure these things? SQL Profiler is showing me the application name is PHP5, so probably register page or login panel injection..

how to do a search and replace for a string in mssql 2012

I am having to find and replace a substring over all columns in all tables in a given database.
I tried this code from sqlserver 2012 ssms but resulting in errors from http://www.dbtalks.com/uploadfile/anjudidi/find-and-replace-string-values-in-all-tables-and-column-in-s/ Find and Replace string Values in All Tables and column in SQL Serve
I think its for older version, it having problems with some of the tables names that start with a number: example dbo.123myTable
Appreciate all the help in advance
Error Print:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.153'.
UPDATE dbo.153Test2dev SET [ALCDescription] = REPLACE(convert(nvarchar(max),[ALCDescription]),'TestsMT','Glan') WHERE [ALCDescription] LIKE '%SherlinMT%'
Updated: 1
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.153'.
UPDATE dbo.153TypeTest2 SET [FormTypeDescription] = REPLACE(convert(nvarchar(max),[FormTypeDescription]),'TestsMT','Glan') WHERE [FormTypeDescription] LIKE '%SherlinMT%'
Updated: 1
Just as a guess, to add delimiters to your table names, modify the script you linked to by editing this line:
SET #sqlCommand = 'UPDATE ' + #schema + '.' + #table + ' SET [' + #columnName + '] = REPLACE(convert(nvarchar(max),[' + #columnName + ']),''' + #stringToFind + ''',''' + #stringToReplace + ''')'
and change it to
SET #sqlCommand = 'UPDATE [' + #schema + '].[' + #table + '] SET [' + #columnName + '] = REPLACE(convert(nvarchar(max),[' + #columnName + ']),''' + #stringToFind + ''',''' + #stringToReplace + ''')'
Are you sure table names may begin with a digit? If so, include them in '[' ']', like
UPDATE [dbo].[153TypeTest2].....
based in the code you linked to, try this:
SET #sqlCommand = 'UPDATE [' + #schema + '].[' + #table + '] SET [' + .....
--add square braces: ^ ^ ^ ^
You should bracket your table name in the same way as the column name in the update query (see #table now has brackets):
SET #sqlCommand = 'UPDATE ' + #schema + '.[' + #table + '] SET [' + #columnName + '] =
REPLACE(convert(nvarchar(max),[' + #columnName + '])

How to run INstead of trigger on all my tables in my database with even field?

i just want to use a trigger instead of insert and update to run on all my tables?
how to do it?
please help me
In SQL Server you can use triggers on DML operations (so per table) as well as on the entire database (DDL trigger). I imagine the syntax is more or less the same for other systems.
The syntax for the first is:
CREATE TRIGGER name ON table
[FOR/AFTER/INSTEAD OF]
[INSERT, UPDATE, DELETE]
AS
BEGIN
--SQL statements
...
END
DDL triggers are not used as much, mostly for auditing but there are better ways to do audit. Anyway, check out this article with some examples.
Sound like it is necessary to create trigger for each table in your database. You can dynamically create a SQL statement on the tables loop and then run that command.
Simple example (Output results in text format)
DECLARE #triggerName nvarchar(50) = 'triggerName'
SELECT 'IF OBJECT_ID(''' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME(#triggerName) + ''')' +
' IS NOT NULL DROP TRIGGER ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' +
QUOTENAME(#triggerName) + CHAR(13) + CHAR(10) +
'GO' + CHAR(13) + CHAR(10) +
'CREATE TRIGGER ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' +
QUOTENAME(#triggerName) + ' ON ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' +
QUOTENAME(OBJECT_NAME(object_id)) + CHAR(13) + CHAR(10) +
'INSTEAD OF INSERT, UPDATE' + CHAR(13) + CHAR(10) +
'AS' + CHAR(13) + CHAR(10) +
'BEGIN' + CHAR(13) + CHAR(10) +
' SELECT ''your_logic''' + CHAR(13) + CHAR(10) +
'END' + CHAR(13) + CHAR(10) +
'GO' + CHAR(13) + CHAR(10) +
'' + CHAR(13) + CHAR(10)
FROM sys.tables

SQL Server - Give a Login Permission for Read Access to All Existing and Future Databases

I have a stored procedure that finds all the existing databases and reads from a table in each one.
Is there a way I can give a login read access to all databases, and to all future databases i.e., I won't have to do anything when a new database is added?
Is there a server role that would work? Is there a way to make a SQL agent job add the permissions on any new databases? Or is there some other method?
For new databases, add the user in the model database. This is used as the template for all new databases.
USE model
CREATE USER ... FROM LOGIN...
EXEC sp_addrolemember 'db_datareader', '...'
For existing databases, use sp_MSForEachDb
EXEC sp_MSForEachDb '
USE ?
CREATE USER ... FROM LOGIN...
EXEC sp_addrolemember ''db_datareader'', ''...''
'
USE [master]
GO
--IF Not EXISTS (SELECT * FROM syslogins where loginname = 'replace with Login name ')
--CREATE LOGIN [replace with Login name ] FROM WINDOWS WITH DEFAULT_DATABASE=[master]
--GO
DECLARE #SQL VARCHAR(MAX)
DECLARE #DatabaseName VARCHAR(255)
DECLARE crFetch CURSOR FOR
--SELECT NAME FROM SYSDATABASES WHERE name in
--('master','model','tempdb','msdb','distribution')
SELECT NAME FROM SYS.DATABASES WHERE name not in
('master','model','tempdb','msdb','distribution')
OPEN crFetch
FETCH NEXT FROM crFetch INTO #DatabaseName
WHILE ##FETCH_STATUS <> -1
BEGIN
SET #SQL =
'USE [' + #DatabaseName + ']' +
'if not exists (select name from sysusers where name='+ ''''+ 'replace with Login name '+ ''''+ ')' +
'CREATE USER [replace with Login name ] FOR LOGIN [replace with Login name ]' +
'EXEC sp_addrolemember N' + '''' + 'db_ETL' + '''' + ', N' + '''' + 'replace with Login name ' + '''' +'
'
--'EXEC sp_addrolemember N' + '''' + 'db_datareader' + '''' + ', N' + '''' + 'replace with Login name ' + '''' +
--'if not exists(select name from sysusers where name='+ ''''+ 'db_executor'+''''+ 'and issqlrole=1)' +
--'create ROLE db_executor' + ' ' +
--'GRANT EXECUTE TO db_executor' + ' ' +
--'EXEC sp_addrolemember N' + '''' + 'db_executor' + '''' + ', N' + '''' + 'replace with Login name ' + '''' +'
--PRINT #SQL
EXEC(#SQL)
FETCH NEXT FROM crFetch INTO #DatabaseName
END
CLOSE crFetch
DEALLOCATE crFetch