As I said in a comment, server-level permissions are deleted the moment you use impersonation.
There are two ways around this:
Bad and fast way:
Set your database to ON. He will do his job. But if you do not fully understand what this is doing, then my advice should have been NOT to do this.
however, here is the code:
ALTER DATABASE [YourDatabase] SET TRUSTWORTHY ON;
Nice but slower way
This is much more accurate and does not have any unpleasant safety side effects.
What you do is that you sign your stored procedure with a certificate. You create a user from this certificate in the databasse. You give this user the correct permissions for your table in the database. You also create a login from the same certificate and grant them input permissions.
Since you sign a saved process with this certificate, every time sp is launched, it runs in the context of this user and registers where it is created from this certificate.
The following steps are performed:
Create a certificate in the main
create login from this certificate
Granting Administrator Rights for this Login
Now you need the exact same certificate in your user database, so we have a few extra steps to complete
now we can complete the work
- create user from certificate
- grant table permissions to this user
- delete as a condition from the stored procedure
- Sign your stored procedure with a certificate
here is the code:
USE master go CREATE CERTIFICATE BulkInsertCert ENCRYPTION BY PASSWORD = 'NicePassword!0' WITH SUBJECT = 'Gives Bulk Insert Privilegde' go CREATE LOGIN BulkInsert_CertLogin FROM CERTIFICATE BulkInsertCert go GRANT ADMINISTER BULK OPERATIONS TO BulkInsert_CertLogin go BACKUP CERTIFICATE BulkInsertCert TO FILE = '[your directory]\BulkInsertCert.cer' WITH PRIVATE KEY (FILE = '[your directory]\BulkInsertCert.pvk' , ENCRYPTION BY PASSWORD = 'EvenNicerPassword!0', DECRYPTION BY PASSWORD = 'NicePassword!0') go USE [YourDatabase] CREATE CERTIFICATE BulkInsertCert FROM FILE = '[your directory]\BulkInsertCert.cer' WITH PRIVATE KEY (FILE = '[your directory]\BulkInsertCert.pvk', DECRYPTION BY PASSWORD = 'EvenNicerPassword!0', ENCRYPTION BY PASSWORD = 'TheVeryBestPasswordThereIs!0') go
Final Note:
Please replace your directory with the path where you are sure that the sql service account has received write permission!
Make sure you delete the exported certificates after you configure.