# Replacing layer ArcSDE connection

I am very new to using Python...

I have an MXD with all of my layer files in it. They are grouped by category etc. Each layer file references a dataset within my SDE. My SDE has two different connections, Admin and View. Admin allows administration of all feature classes. View is a select only connection.

All of my layers should be connected to feature classes in the View SDE connection. However I have over 70 layers which reference the Admin SDE connection. How do I change this using Python. I do not want to manually change the source SDE connection and then save a new layer.

Would it also be possible to overwrite the layer file using its current file information and location?

I have tried the following bits of code but no luck...

import arcpy
mxd = arcpy.mapping.MapDocument("CURRENT")
for lyr in arcpy.mapping.ListLayers(mxd):
lyr.replaceDataSource(r"C:\Users\x939062\AppData\Roaming\ESRI\Desktop10.2\ArcCatalog\MMO_View.sde", "SDE_WORKSPACE",,"False")


I have also tried the following, but again no luck...

import arcpy
mxd = arcpy.mapping.MapDocument("CURRENT")
for lyr in arcpy.mapping.ListLayers(mxd):

• Also, I should have made it clearer in my question, but the layer files im refereing to are lyr files within my mxd. They reference feature classes within my SDE connection. I have two different connections with different privliedge rights, admin and view. I need to make sure the lyr files reference the view sde connection rathat than the admin. – MacroZED Jun 1 '15 at 14:18

Was just doing this yesterday. You should just be able to call findAndReplaceWorkspacePaths on your mxd object. Below will loop through the dict objects in the workspacePathMap array and replace old with new:

mxdFn = r"C:\path\to\original\mxd.mxd"
newMxdFn = r"C:\path\to\new\mxd.mxd"

workspacePathMap = [{
"old": r'C:\path\to\old\conn.sde',
"new": r'C:\path\to\new\conn.sde'
},
{
"old": r'D:\old-dir',  # shp, fgdb
"new": r'D:\new--dir'
}]

def updateDataSources(mxdFn, workspacePathMap, newMxdFn):
print "Repathing {0}".format(mxdFn)
mxd = arcpy.mapping.MapDocument(mxdFn)
for ws in workspacePathMap:
mxd.findAndReplaceWorkspacePaths(ws["old"], ws["new"], False)
mxd.saveACopy(newMxdFn)

updateDataSources(mxdFn, workspacePathMap, newMxdFn)

• Is "mxdFn" the MXD which has all the layers? And should this be referenced using its full location r'C:\\\.mxd. Would it be possible to help me understand what you've written using an example of sorts. – MacroZED Jun 1 '15 at 14:10
• @Zahir_Ibrahim - correct, mxdFn is the original MXD that you want to repath, newMxdFn is the copy that you save to. – Chad Cooper Jun 1 '15 at 15:15
• @Zahir_Ibrahim - edited the code for clarification on usage. – Chad Cooper Jun 1 '15 at 15:22