Ever since Microsoft released Dynamics NAV 2013, there has been a discussion on the best way to create a user in a restored database.
The problem is this:
When a SQL backup is made and ported to a different environment, the Windows or Active Directory users that were created in the old environment are not necessarily created in the new environment.
It is always possible to restore the backup on the new SQL server, but that does not give me access to the database.
The easy way is to delete all information in four tables, but that will delete all existing users. If they are not needed then it is no problem, but if we want to keep the existing users then, this is not an option.
Deleting all users can be done running the following script.
USE [Database]
delete from [dbo].[User]
delete from [dbo].[Access Control]
delete from [dbo].[User Property]
delete from [dbo].[Page Data Personalization]
delete from [dbo].[User Default Style Sheet]
delete from [dbo].[User Metadata]
delete from [dbo].[User Personalization]
GO
If the user names are precisely the same just with a different domain then it is possible to “update” the windows security id with this script.
UPDATE User SET [Windows Security ID] = '<new_Windows_security_id>' where [user name] = '<username>';
GO
Combined with the syslogin table and a little SQL magic, it may even be possible to change all users from one domain to another and from one Windows Security id to another.
But what if I want a script to run, that will:
- Create a user on the SQL server
- Generate a random User SID
- Create the user in the database
- Add a role to the user
- Give permission to the user in the new database
In one go.
It took a bit of Googling and help from dailycoding.com, Daniel Rimmelzwaan on Mibuso and other resources to compile this script, which I pass on to you without any guaranties and to serve as inspiration. Just add information on the username, the database and the permissions you want to assign to the user and run the script.
And you are in.
USE [master]
/* Declare variables */
DECLARE @USERSID uniqueidentifier, @USERSIDTXT varchar(50), @PERMISSION varchar(50), @USERNAME varchar(50), @WINDOWSSID varchar(119), @DATABASENAME varchar(50), @BinSid VARBINARY(100), @t nvarchar(4000)
/* Username, database and permissions must be entered here */
SET @USERNAME = 'N4T\invoice'
SET @DATABASENAME = 'N4Tdemo'
SET @PERMISSION = 'SUPER'
/* Generate a random unique id */
SELECT NEWID()
SET @USERSID = NEWID()
SET @USERSIDTXT = CONVERT(VARCHAR(50), @USERSID)
/* Create Loin if necessary */
BEGIN TRY
SET @t = N'CREATE LOGIN [' + @USERNAME + '] FROM WINDOWS'
exec sys.sp_executesql @t
END TRY
BEGIN CATCH
END CATCH
/* Get the WindowsSID from the SQL server */
SET @BinSid = (SELECT sid FROM syslogins where loginname=@USERNAME)
/* Convert the uniqueidentifier to NAV SID */
IF LEN(@BinSID) % 4 <> 0 raiserror('User Name not found', 20, -1) with log
DECLARE @i AS INT
DECLARE @j AS INT
SELECT @WINDOWSSID = 'S-'
+ CONVERT(VARCHAR, CONVERT(INT, CONVERT(VARBINARY, SUBSTRING(@BinSID, 1, 1))))
SELECT @WINDOWSSID = @WINDOWSSID + '-'
+ CONVERT(VARCHAR, CONVERT(INT, CONVERT(VARBINARY, SUBSTRING(@BinSID, 3, 6))))
SET @j = 9
SET @i = LEN(@BinSID)
WHILE @j < @i
BEGIN
DECLARE @val BINARY(4)
SELECT @val = SUBSTRING(@BinSID, @j, 4)
SELECT @WINDOWSSID = @WINDOWSSID + '-'
+ CONVERT(VARCHAR, CONVERT(BIGINT, CONVERT(VARBINARY, REVERSE(CONVERT(VARBINARY, @val)))))
SET @j = @j + 4
END
/* Change database */
SET @t = N'USE [' + @DATABASENAME +']'
exec sys.sp_executesql @t
/* Create user */
SET @t = N'CREATE USER [' + @USERNAME + '] FOR LOGIN [' + @USERNAME + ']'
exec sys.sp_executesql @t
/* Add role to user */
SET @t = N'sp_addrolemember ' + '''' + 'db_owner' + ''''+ ', ' + '''' + @USERNAME + ''''
exec sys.sp_executesql @t
/* Insert user in database */
SET @t = N'INSERT INTO [' + @DATABASENAME +'].[dbo].[User] '+
'([User Security ID]
,[User Name]
,[Full Name]
,[State]
,[Change Password]
,[Expiry Date]
,[Windows Security ID]
,[License Type]
,[Authentication Email])
VALUES
(' + '''' + @USERSIDTXT + '''' +
',' + '''' + @USERNAME + '''' +
',' + '''' + '''' +
',' + '0' +
',' + '0' +
',' + '''' + '1753-01-01 00:00:00.000' + '''' +
','+ ''''+ @WINDOWSSID + '''' +
',' + '0' +
',' + '''' + '''' +')'
exec sys.sp_executesql @t
/* Add permissions */
SET @t = 'INSERT INTO [' + @DATABASENAME +'].[dbo].[Access Control]
([User Security ID]
,[Role ID]
,[Company Name])
VALUES
(' + '''' + @USERSIDTXT + '''' +
',' + '''' + @PERMISSION + '''' +
',' + '''' + '''' + ')'
exec sys.sp_executesql @t
/* Add User Property */
SET @t = 'INSERT INTO [' + @DATABASENAME +'].[dbo].[User Property]
([User Security ID]
,[Password]
,[Name Identifier]
,[Authentication Key]
,[WebServices Key]
,[WebServices Key Expiry Date]
,[Authentication Object ID])
VALUES
(' + '''' + @USERSIDTXT + '''' +
',' + '''' + '''' +
',' + '''' + '''' +
',' + '''' + '''' +
',' + '''' + '''' +
',' + '''' + '1753-01-01 00:00:00.000' + '''' +
',' + '''' + '''' +')'
exec sys.sp_executesql @t
GO
Alright you lot, spotted baji999casino. Thinking about trying my luck. Might be a bit of alright. What do you reckon? Have at it baji999casino.
Win99? Yeah, I downloaded a few games there. Pretty slick setup. Fast downloads too! Worth trying taigamewin99.
Plusph11, huh? New one to me. Gonna take a look around. The layout is pretty clean. Hope the odds are good. Wish me luck! plusph11
фильмы онлайн без рекламы вестерны смотреть онлайн бесплатно
the best adult generator long term ai companion create erotic videos, images, and virtual characters. flexible settings, high quality, instant results, and easy operation right in your browser. the best features for porn generation.
сервис рекламных рассылок сервис для email рассылок российский
bookmaker melbet telecharger melbet apk
bookmaker 1win telecharger 1win apk
сколько цена квартиры жк светский лес официальный сайт
Нужен проектор? http://projector24.ru большой выбор моделей для дома, офиса и бизнеса. Проекторы для кино, презентаций и обучения, официальная гарантия, консультации специалистов, гарантия качества и удобные условия покупки.
характеристики проектора интернет-магазин проекторов
купить квартиру купить квартиру жк светский лес
химчистка зимней обуви химчистка обуви
Играешь в казино? ап икс скачать Слоты, рулетка, покер и live-дилеры, простой интерфейс, стабильная работа сайта и возможность играть онлайн без сложных настроек.
Лучшее казино ап икс официальный играйте в слоты и live-казино без лишних сложностей. Простой вход, удобный интерфейс, стабильная платформа и широкий выбор игр для отдыха и развлечения.
Лучшее казино ап икс играйте в слоты и live-казино без лишних сложностей. Простой вход, удобный интерфейс, стабильная платформа и широкий выбор игр для отдыха и развлечения.
заклепка вытяжная 4х10 заклепка вытяжная
За год использования кракен маркет даркнет ни разу не подвёл с доступом
дизайн одноэтажного дома дизайн ремонта коттеджа
дизайн залы в квартире дизайн 2 комнатной кв
полотенцесушитель лесенка полотенцесушитель водяной
7lggame, huh? Looks like it has quite a few options. Could be a decent choice if you’re looking to pass some time. Here you go: 7lggame
Citibet88login is the name of the game. Fast, secure, and gets you straight where you need to be. Say goodbye to login headaches The support staff is friendly. Check it here: citibet88login
Lodi777login came through for me. Was having trouble getting in, but this fixed everything. Login is easy! Give it a try, you won’t regret it Easy peasy: lodi777login
шумоизоляция арок авто https://shumoizolyaciya-arok-avto-77.ru
авто шиномонтаж выездной https://vyezdnoj-shinomontazh-77.ru
Cobalt Corner Store – The product lineup is well curated and the purchase process is seamless.
the wanderlust warehouse – Each visit fills me with excitement about future travels.
the modern fryer shop – It gives me confidence to try new recipes quickly.
peachparlor collection – The shop feels cheerful, with a layout that makes purchasing easy.
mist shop hub – A minimalist approach with tidy product presentation makes shopping stress-free.
Domain Den Store – The structure is simple and moving around the site is very intuitive.
click to explore Apparel Ambergris – Everything is displayed attractively, and navigating is smooth.
Здравствуйте дорогие друзья! На первом этапе нужно разобраться — крыша производственного цеха. Хочешь качественно — вот проверенную компанию: https://montazh-membrannoj-krovli-spb.ru. В большинстве случаев большие площади — требуют особого подхода. Короче, сложная конфигурация — соответственно важен опыт бригады. Мы используем профессиональное оборудование. Вот потому что это работает. Что в итоге: это отличные параметры.
шумоизоляция авто
Enterprise Bond Solutions Online Hub – Intuitive pages and logical layout make browsing effortless.
Xorya Design Hub – Tidy interface and modern layout make navigating the site intuitive.
Yavex Store – Pages load quickly, and the site runs very smoothly.
your Click to Explore Innovations – Logical structure and clear menus make browsing effortless.
Xorya Online Picks – Neat layout and modern styling help make finding items effortless.
creative product shop – Distinctive pieces here immediately caught my curiosity.
your TrustedEnterpriseFramework hub – Smooth interface and structured layout make reading effortless.
clickrank site – Content reads clearly, helpful examples made concepts easy to grasp.
Ardenzo essentials – The neat layout makes it easy to find exactly what you need.
1911 PHL updates page – Stay informed with concise and clearly presented information.
winteraisle.shop – The layout is tidy and browsing through the site is effortless.
explore Terra Vendor shop – Costs are reasonable and the selection is quite solid.
check out Cove Vendor – Pages load fast and navigating between sections is easy.
PP4FDR Action Portal – Insightful and clearly written explanations make the objectives easy to grasp.
nicheninja site – Navigation felt smooth, found everything quickly without any confusing steps.
reachly site – Mobile version looks perfect; no glitches, fast scrolling, crisp text.
leadzo site – Color palette felt calming, nothing distracting, just focused, thoughtful design.
leadora site – Mobile version looks perfect; no glitches, fast scrolling, crisp text.
Youth Education Network – Inspires young learners through interactive activities and fresh concepts.
RoseCrate marketplace – Pleasant experience, I’ll return to check more items.
Night Out Decisions – Clever idea and the lively discussions make browsing worthwhile.
NuPurple Pricing Options – Transparent pricing and helpful notes make selecting a plan effortless.
PineVendor website – Clean, fast-loading pages give a very professional feel.
ZenMarket – Love the calm look and how easy it is to understand each item.
unique novelty corner – So many charming bits and pieces, I’ll be back for more.
artisan harbor goods – The overall design feels welcoming and creatively put together.
orderquill.shop – The design is minimal and tidy, which makes browsing effortless.
efficient vendor hub – The store gives a trustworthy impression, and checkout looks easy to follow.
Browse Goods Quarry – An appealing selection with prices that don’t seem too high.
cometcrate shopping corner – Engaging product mix, thoughtfully curated to capture attention.
adster – Pages loaded fast, images appeared sharp, and formatting stayed consistent.
reacho – Content reads clearly, helpful examples made concepts easy to grasp.
offerorbit – Pages loaded fast, images appeared sharp, and formatting stayed consistent.
For those seeking an exceptional online gaming experience, us.com](https://maxispin.us.com/) stands out as a premier destination. At Maxispin Casino, players can enjoy a vast array of pokies, table games, and other thrilling options, all accessible in both demo and real-money modes. The casino offers attractive bonuses, including free spins and a generous welcome offer, along with cashback promotions and engaging tournaments. To ensure a seamless experience, Maxispin provides various payment methods, efficient withdrawal processes, and reliable customer support through live chat. Security is a top priority, with robust safety measures and a strong focus on responsible gambling tools. Players can easily navigate the site, with detailed guides on account creation, verification, and payment methods. Whether you’re interested in high RTP slots, hold and win pokies, or the latest slot releases, Maxispin Casino delivers a user-friendly and secure platform. Explore their terms and conditions, read reviews, and discover why many consider Maxispin a legitimate and trustworthy choice in Australia.
The platform provides state-of-the-art tools to create unique and captivating text content.
**Features of MaxiSpin.us.com**
MaxiSpin.us.com boasts the ability to generate content in multiple languages as one of its key features.
**Benefits of Using MaxiSpin.us.com**
With MaxiSpin.us.com, creating compelling content has never been easier or more efficient.
TinyHarbor Online – Some really nice offers, bookmarking for future visits.
Inqora Online – Very easy to navigate and pages respond fast.
stackhq – Found practical insights today; sharing this article with colleagues later.
cloudhq – Bookmarked this immediately, planning to revisit for updates and inspiration.
bytehq – Overall, professional vibe here; trustworthy, polished, and pleasantly minimal throughout.
stackops – Appreciate the typography choices; comfortable spacing improved my reading experience.
cloudopsly – Navigation felt smooth, found everything quickly without any confusing steps.
Explore Iventra – Clean design and checkout worked without issues.
Discover Wavento – Items are easy to find and the interface is clean.
Click Hyvora – Easy navigation and everything loads without lag.
keywordcraft – Color palette felt calming, nothing distracting, just focused, thoughtful design.
adscatalyst – Content reads clearly, helpful examples made concepts easy to grasp.
serpstudio – Overall, professional vibe here; trustworthy, polished, and pleasantly minimal throughout.
leadspike – Bookmarked this immediately, planning to revisit for updates and inspiration.
trafficcrafter – Loved the layout today; clean, simple, and genuinely user-friendly overall.
шумоизоляция торпеды
шумоизоляция дверей авто
Find Exclusive Items – Navigation is simple and the checkout process feels smooth and reliable.
Check Out Products – Pages respond instantly and browsing through categories is intuitive.
datadev – Appreciate the typography choices; comfortable spacing improved my reading experience.
trycloudy – Bookmarked this immediately, planning to revisit for updates and inspiration.
Start Shopping Here – New arrivals appear often, making each visit exciting and fun to browse.
gobyte – Navigation felt smooth, found everything quickly without any confusing steps.
getbyte – Color palette felt calming, nothing distracting, just focused, thoughtful design.
usebyte – Bookmarked this immediately, planning to revisit for updates and inspiration.
clovermarket.shop – Great selection of items and finding what I want is simple and fast.
getstackr – Navigation felt smooth, found everything quickly without any confusing steps.
cloudster – Pages loaded fast, images appeared sharp, and formatting stayed consistent.
Check Out Products – Support team was efficient and clarified everything I needed to know.
explore lemon loft store – Layout appears minimal, tidy, and convenient for checking products.
Find Exclusive Items – Browsing feels easy and intuitive, making shopping enjoyable.
Shop Copper Crate Online – Everything is neatly organized and product details are easy to read.
dataworks – Bookmarked this immediately, planning to revisit for updates and inspiration.
kubexa – Mobile version looks perfect; no glitches, fast scrolling, crisp text.
cloudiva – Bookmarked this immediately, planning to revisit for updates and inspiration.
stackora – Loved the layout today; clean, simple, and genuinely user-friendly overall.
devonic – Mobile version looks perfect; no glitches, fast scrolling, crisp text.
codefuse – Mobile version looks perfect; no glitches, fast scrolling, crisp text.
securia – Mobile version looks perfect; no glitches, fast scrolling, crisp text.
Многих интересует, где скачать базы для xrumer, ведь важно работать с актуальными данными.
codestackr – Content reads clearly, helpful examples made concepts easy to grasp.
codepushr – Content reads clearly, helpful examples made concepts easy to grasp.
devpush – Appreciate the typography choices; comfortable spacing improved my reading experience.
gitpushr – Color palette felt calming, nothing distracting, just focused, thoughtful design.
shipkit – Appreciate the typography choices; comfortable spacing improved my reading experience.
debugkit – Bookmarked this immediately, planning to revisit for updates and inspiration.
testkit – Appreciate the typography choices; comfortable spacing improved my reading experience.
logkit – Pages loaded fast, images appeared sharp, and formatting stayed consistent.
promptkit – Found practical insights today; sharing this article with colleagues later.
modelops – Color palette felt calming, nothing distracting, just focused, thoughtful design.
deploykit – Appreciate the typography choices; comfortable spacing improved my reading experience.
databrain – Pages loaded fast, images appeared sharp, and formatting stayed consistent.
mlforge – Found practical insights today; sharing this article with colleagues later.
taskpipe – Overall, professional vibe here; trustworthy, polished, and pleasantly minimal throughout.
smartpipe – Loved the layout today; clean, simple, and genuinely user-friendly overall.
securekit – Color palette felt calming, nothing distracting, just focused, thoughtful design.
threatlens – Appreciate the typography choices; comfortable spacing improved my reading experience.
keyvaulty – Bookmarked this immediately, planning to revisit for updates and inspiration.
auditkit – Mobile version looks perfect; no glitches, fast scrolling, crisp text.
smartbyte – Mobile version looks perfect; no glitches, fast scrolling, crisp text.
techsphere – Navigation felt smooth, found everything quickly without any confusing steps.
nanotechhub – Found practical insights today; sharing this article with colleagues later.
keyvaulty – Found practical insights today; sharing this article with colleagues later.
clicktechy – Loved the layout today; clean, simple, and genuinely user-friendly overall.
quickbyte – Pages loaded fast, images appeared sharp, and formatting stayed consistent.
pixelengine – Found practical insights today; sharing this article with colleagues later.
vendor collective homepage – Clean pages and clear categories make browsing easy
Vendor Hub Picks – Friendly layout, makes exploring vendors intuitive.
the Glade Meadow Outlet – Easy to recall and inviting, giving a pleasant online impression.
futurestack – Appreciate the typography choices; comfortable spacing improved my reading experience.
bitzone – Pages loaded fast, images appeared sharp, and formatting stayed consistent.
Glass Ridge Finds – Cheerful and classy, perfect for highlighting unique products.
codehive – Loved the layout today; clean, simple, and genuinely user-friendly overall.
the Glass Willow Trading – Formal yet inviting, giving a strong sense of credibility.
tronbyte – Color palette felt calming, nothing distracting, just focused, thoughtful design.
futurebyte – Navigation felt smooth, found everything quickly without any confusing steps.
Golden Harbor Hub Online – Contemporary and inviting, giving a sense of accessibility and community.
TimberCrateOnline – Browsed quickly, the layout feels organized and smooth.
Golden Stone Shop – Clear and straightforward, giving a no-nonsense, reliable impression.