rename all mapped domain logins for instance - sql-server

I am looking for a way to rename 100+ mapped domain groups in SQL server.
something like this:
old:
DOMAIN\Group01
DOMAIN\Group02
DOMAIN\Group03
DOMAIN\Group04
DOMAIN\Group05
new:
DOMAIN\Group01_OLD
DOMAIN\Group02_OLD
DOMAIN\Group03_OLD
DOMAIN\Group04_OLD
DOMAIN\Group05_OLD
Is there a fast way to bulk rename the logins in SQL?

You may try following.
In SSMS run the script:
select
'alter login ' + quotename(name) + ' with name = ' + quotename(name + '_OLD')
from
sys.syslogins
where
name like 'DOMAIN\Group%'
Copy results into clipboard and paste into SSMS New Query tab. Check the commands generated and then run.

Related

Execute sp_rename SQL command using pypyodbc

Initially I had used the following command to rename SQL tables:
Q = """sp_rename {}, {}""".format(OLD_TABLE_NAME,NEW_TABLE NAME)
However, this caused an "Lock request time out period exceeded" error, which I believe was due to the lack of "commit" at the end of the query (although I am not confident on this).
So instead, I adopted a new query (adapted from this question).
Q2 = """BEGIN TRANSACTION
GO
EXECUTE sp_rename N'{}', N'{}', 'OBJECT'
GO
ALTER TABLE {} SET (LOCK_ESCALATION = TABLE)
GO
COMMIT""".format(OLD_TABLE_NAME,NEW_TABLE NAME,NEW_TABLE NAME)
However, I'm now getting a ProgrammingError saying "Incorrect syntax near 'GO'."
Do I need to remove some parts of Q2 for the query to work? Or is some other part wrong?
Below are the two functions I use to connect to my SQL server:
from sqlalchemy import create_engine
import pypyodbc as pp
server1 = {
'drivername': 'mssql+pyodbc',
'servername': 'SERVERNAME',
#'port': '5432',
'username': 'WebAccess',
'password': ':|Ax-*6_6!5H',
'driver': 'SQL Server Native Client 11.0',
'trusted_connection': 'yes',
'legacy_schema_aliasing': False
}
def getEngine(servername, database):
DB = server1
#Create connection to SQL database
DB['database'] = database
servername1 = servername.lower()
engine = create_engine('mssql+pyodbc://' + DB['username'] + ':' + DB['password'] + '#' + DB['servername'] + '/' + DB['database'] + '?' + 'driver=' + DB['driver'])#, echo=True)
return engine
def SQLcommand(query,servername,database):
connection = pp.connect("""Driver={SQL Server};Server=""" + servername + """;Database=""" + database + """;uid=USERNAME;pwd=PASSWORD""")
cursor = connection.cursor()
cursor.execute(query)
connection.commit()
connection.close()
This works for me based on the note in the SQLAlchemy Docs:
sql_stmt = f"""EXECUTE sp_rename '{table2}', '{table1}';"""
with connection.begin() as conn:
conn.execute(text(sql_stmt))
Alright dude, you got a few problems here.
pypyodbc is something you should move away from. That library was
all the rage a while ago, but to my knowledge it's not getting many
commits anymore, google is moving away from it, in my build we moved
away from it for a number of reasons. It was great while it lasted
but I think its on the out.
You cannot use 'GO' in a query. 'GO' is not a tsql statement, its a sqlcmd command - thus it doesn't work with odbc. 'GO' essentially just breaks the code into batches, so to do this not using 'GO' you need to run multiple batches, something like:
conn = engine.connect()
tran = conn.transaction()
conn.execute(f"EXECUTE sp_rename N'{OLD_TABLE_NAME}', N'{NEW_TABLE_NAME}', 'OBJECT'")
conn.execute(f"ALTER TABLE {NEW_TABLE_NAME} SET LOCK_ESCALATION = TABLE")
tran.commit()
I'm sure there's more going on here as well, but hopefully this'll get you going.
For anyone still wondering how to solve the problem, I fixed Jamie Marshall's answer in order to adapt it to new transaction api:
conn = engine.connect()
def rename(cnxn):
rename_query = f"EXECUTE sp_rename N'{OLD_TABLE_NAME}', N'{NEW_TABLE_NAME}', 'OBJECT'"
cnxn.execute(rename_query)
conn.transaction(rename)

Obtain the Filename for the Current Running SQL script - MS SQL Server 2008

I have a system that auto-generates SQL files for me in the format:
CALLID_DATE_SCRIPTYPE.sql - eg 108312_20170913_DeleteRubbishData.sql
I want to grab the call id and current user automatically without having to specify it again.
I know how to grab user, but not sure if it is possible to grab filename.
Anyone know if this is possible?
EXAMPLE:
DECLARE #File NVARCHAR(100) = CURRENTFILENAMEORWHATEVERTHEFUNCTIONISCALLED();
DECLARE #AuditData NVARCHAR(100) = 'Call: ' + LEFT(#File, CHARINDEX('_', #File) - 1)
+ ', User: ' + SUSER_NAME();
PRINT #AuditData
OUTPUT:
Call: 108312, User: Sys\JSmith

TSQL: access user data from LDAP

I have an Active Directory (LDAP) that stores user information. I'm trying to access it using TSQL, but I'm having authentication problems.
The LDAP looks like this (I edited the data):
The user has the following properties:
Now, I'm trying to get the info from this user through a TSQL query from SQL Server using OPENROWSET like so:
SELECT *
FROM
OPENROWSET('ADSDSOObject','adsdatasource'; 'domain.com.io\test';'the_sha1_pass',
'SELECT givenname
FROM ''LDAP://domain.com.io/ou=Users,
dc=domain,dc=com,dc=io'' WHERE givenname = ''Test''
')
But when I execute it I get the following error:
Server: Msg 7399, Level 16, State 1, Line 1 OLE DB provider '
ADSDSOObject ' reported an error. The provider indicates that the user
did not have the permission to perform the operation.
Now, I don't know if I have to send the authentication of the user I'm trying to query over, or the credentials I use to connect with LDAPAdmin. And if I have to send it, should I send the pass already encrypted or without encryption?
Thanks.
You can change your OPENROWSET query as follows by removing the username and password
SELECT * FROM OPENROWSET('ADSDSOObject','adsdatasource',
'SELECT givenname
FROM ''LDAP://kodyaz.com/DC=kodyaz,DC=com'' WHERE givenname = ''KODYAZ''
')
Or as an alternative, you can try following query structure
SELECT * FROM OpenQuery(ADSI, 'SELECT * FROM ''LDAP://kodyaz.com/DC=kodyaz,DC=com'' WHERE objectCategory=''user'' AND givenname = ''KODYAZ'' ')
I added user objectCategory in WHERE clause with givenname parameter in OpenQuery command
Before running above Select statement, you can add LDAP as linked server in SQL Server as shown in referred tutorial
EXEC sp_addlinkedserver 'ADSI', 'Active Directory Service Interfaces', 'ADSDSOObject', 'adsdatasource'

Informatica: downloading image data type to disk

I have a table in sql server that contain two columns
Filename char datatype
File image datatype
Requirement is to download all the data to the disk , is it possible using informatica and if yes how?
For example, if there are two rows in the table:
sal_1.pdf, <<image data>>
sal_2.pdf, <<image data>>
and it needs to be pushed to disk D:/file_dump directory then D:/file_dump should have two files with the names sal_1.pdf and sal2.pdf.
You could use T-SQL and bcp (link 1, link 2) like this:
1) Write a T-SQL script (using SQL Server Management Studio) to generate all shell/bcp commands
SET NOCOUNT ON;
SELECT 'bcp "SELECT y.File FROM Schema.Table y WHERE y.IDColumn='
+ CONVERT(VARCHAR(11),x.IDColumn)
+ ' queryout "D:\file_dump\'
+ x.FileName
+ '" -N -S SqlServerInstance -T -d "DatabaseName"'
FROM Table x
Press Ctrl+T (Text results)
Press F5 (Execute)
Press F6 (It activates the Results (text) panel
Press Ctrl+A (Select All)
Press Ctrl+C (Copy)
2) Create a new text file (Win Key+Notepad+Enter), Ctrl+V (Paste), Save As ... -> dump_pdf.bat
3) Execute dump_pdf.bat file

In SQL Server 2005, is there an easy way to "copy" permissions on an object from one user/role to another?

I asked another question about roles and permissions, which mostly served to reveal my ignorance. One of the other outcomes was the advice that one should generally stay away from mucking with permissions for the "public" role.
OK, fine, but if I've already done so and want to re-assign the same permissions to a custom/"flexible" role, what's the best way to do that? What I've done so far is to run the Scripting wizard, and tell it to script object permissions without CREATE or DROP, then run a find-replace so that I wind up with a lot of "GRANT DELETE on [dbo.tablename] TO [newRole]". It gets the job done, but I feel like it could be prettier/easier. Any "best practice" suggestions?
Working from memory (no SQL on my gaming 'pooter), you can use sys.database_permissions
Run this and paste the results into a new query.
Edit, Jan 2012. Added OBJECT_SCHEMA_NAME.
You may need to pimp it to support schemas (dbo.) by joining onto sys.objects
SET NOCOUNT ON;
DECLARE #NewRole varchar(100), #SourceRole varchar(100);
-- Change as needed
SELECT #SourceRole = 'Giver', #NewRole = 'Taker';
SELECT
state_desc + ' ' +
permission_name + ' ON ' +
OBJECT_SCHEMA_NAME(major_id) + '.' + OBJECT_NAME(major_id) +
' TO ' + #NewRole
FROM
sys.database_permissions
WHERE
grantee_principal_id = DATABASE_PRINCIPAL_ID(#SourceRole)
AND
-- 0 = DB, 1 = object/column, 3 = schema. 1 is normally enough
class <= 3;
The idea of having a role is that you only need to setup the permissions once. You can then assign users, or groups of users to that role.
It's also possible to nest roles, so that a role can contain other roles.
Not sure if its best practice, but it makes sense that if you have a complex set of permissions, with groups of users that need access to multiple applications you go something like:
NT User -> NT Security Group -> SQL Server Role -> SQL Server Role A, Role B ...

Resources