SQL Exception when executing stored procedure from within Biztalk - sql-server

We have a stored procedure in place that creates a new SSIS execution and starts it:
Declare #execution_id bigint
EXEC [SSISDB].[catalog].[create_execution]
#package_name=N'00 XXXX.dtsx',
#execution_id=#execution_id OUTPUT,
#folder_name=N'XX',
#project_name=N'XXX';
EXEC [SSISDB].[catalog].[start_execution] #execution_id;
When we call this stored procedure logged on using SQL Server Management Studio, this works perfectly. However, when we execute this stored procedure from within BizTalk (as a BTS service account user) we receive this error:
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near '-'.
Incorrect syntax near '-'.
Incorrect syntax near '-'.
Server stack trace:
at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.End(SendAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndRequest(IAsyncResult result)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at System.ServiceModel.Channels.IRequestChannel.EndRequest(IAsyncResult result)
at Microsoft.BizTalk.Adapter.Wcf.Runtime.WcfClient`2.RequestCallback(IAsyncResult result)
The schema we use from BTS to MS SQL:
<?xml version="1.0" encoding="utf-16"?>
<schema xmlns:b="http://schemas.microsoft.com/BizTalk/2003" xmlns:ns0="http://schemas.microsoft.com/Sql/2008/05/TypedProcedures/dbo" elementFormDefault="qualified" targetNamespace="http://schemas.microsoft.com/Sql/2008/05/TypedProcedures/dbo" version="1.0" xmlns="http://www.w3.org/2001/XMLSchema">
<annotation>
<appinfo>
<fileNameHint xmlns="http://schemas.microsoft.com/servicemodel/adapters/metadata/xsd">TypedProcedure.dbo</fileNameHint>
</appinfo>
</annotation>
<element name="StartBifImport">
<annotation>
<documentation>
<doc:action xmlns:doc="http://schemas.microsoft.com/servicemodel/adapters/metadata/documentation">TypedProcedure/dbo/StartBifImport</doc:action>
</documentation>
</annotation>
<complexType>
<sequence />
</complexType>
</element>
</schema>
The BTS service account has the db_owner role on the database where the stored procedure resides, and we have given it explicitly all 'grant' permissions on the SSIS folder and SSIS package.
We can see in the executions table that no execution is created, so something seems to go wrong on that call. When connecting with SQL Profiler we see the same error returning, but without much further context as to what is wrong; leaving is without much trace.
Any pointers/ideas on how the debug or resolve this issue?

I suggest not to use a "Strongly-Typed Procedure" schema, but a "Procedure" schema. The "Strongly-Typed Procedure" from the WCF-SQL adapter has a documented issue with generating the schema for stored procedures with temp tables in it.
The SQL adapter does not support generating metadata for strongly-typed stored procedures that contain temporary tables in their definition. Instead, you should generate metadata for the same procedure from under the Procedures node while using the Add Adapter Service Reference Plug-in or Consume Adapter Service Add-in.
More information can be found here: https://msdn.microsoft.com/en-us/library/dd788435(BTS.10).aspx#BKMK_SQLMetadataStronglyTyped

Create a simple one-way send port that has the same filter (and map, if applicable) as one you are busy debugging, that simply writes to a file. Use the output of the file to confirm the message sent to the WCF-SQL adaptor has the structure it is expecting.
Judging by the schema, it should produce a file with the following content:
<ns0:StartBifImport xmlns:ns0="http://schemas.microsoft.com/Sql/2008/05/TypedProcedures/dbo">
</ns0:StartBifImport>

Related

Surface custom exception messages in SQL Server MDS from a user defined business rule action stored procedure

I've created a stored procedure that is run as a user defined action for a business rule in MDS. I want to be able to surface up the exceptions I have put in the procedure to be visible to the user executing the business rule as a result of their modification.
It seems like in MDS' built in procedures, e.g. [mdm].[udpValidateEntity] they have used:
RAISERROR (N'MDSERR200226|The entity version cannot be validated. It is the target of a sync relationship.', 16, 1);
This, if copied and pasted in my code results in an expected error popup msg
200226:The entity version cannot be validated. It is the target of a sync relationship.
But when I try to implement this using my own error code and message
IF #err_msg IS NOT NULL
BEGIN;
SET #err_msg = N'MDSERR99999|MDS PROC usr.UpdateInvalidValidityRange' + #err_msg;
RAISERROR (#err_msg, 16, 1);
END;
The error message gets replaced by a generic error message:
99999: A database error has occurred. Contact your system administrator.
Is there a way to surface error messages to the UI?

An unexpected method call was made. Ensure that the XML is well formed. The stack trace of the method call was : Void WriteFullEndElement()

Using BizTalk I am trying to insert/update the table in the SQL Server database using the stored procedure. I have created a stored procedure and the Table Type like below
CREATE TYPE dbo.dept_TT AS TABLE
(
dept_name varchar(64),
jax_dept_id char(32)
)
GO
CREATE PROCEDURE [dbo].[uspInsertorUpdateDept]
#dept_TT dept_TT READONLY
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRANSACTION;
UPDATE dep
SET dep.dept_name = dtt.dept_name,
dep.jax_dept_id = dtt.jax_dept_id
FROM [afm].[jax_dept] dep
INNER JOIN #dept_TT dtt ON dep.jax_dept_id = dtt.jax_dept_id
INSERT INTO [afm].[jax_dept](dept_name, jax_dept_id )
SELECT dtt.dept_name, dtt.jax_dept_id
FROM #dept_TT dtt
WHERE NOT EXISTS (SELECT 1
FROM [afm].[jax_dept]
WHERE jax_dept_id = dtt.jax_dept_id)
COMMIT TRANSACTION;
END;
When I execute the stored produre in the SQL Server management studio it insert/updates the records as expected. I am consuming this storedprocedure in the biztalk application and tried to run the application it throws error like
The adapter failed to transmit message going to send port "WcfSendPort_SqlAdapterBinding_Procedures_dbo_Custom_Dep" with URL "mssql://". It will be retransmitted after the retry interval specified for this Send Port. Details:"Microsoft.ServiceModel.Channels.Common.XmlReaderParsingException: An unexpected method call was made. Ensure that the XML is well formed. The stack trace of the method call was : Void WriteFullEndElement().
I enabled the tracking and tried seeing the XML that is sent to the send port and it looks good like below.
<?xml version="1.0" encoding="utf-8"?>
<ns0:uspInsertorUpdateDept xmlns:ns0="http://schemas.microsoft.com/Sql/2008/05/Procedures/dbo" xmlns:ns4="http://schemas.datacontract.org/2004/07/System.Data" xmlns:ns3="http://schemas.microsoft.com/Sql/2008/05/Types/TableTypes/dbo" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ns0:dept_TT>
<ns3:dept_TT>
<ns3:dept_name>lab1</ns3:dept_name>
<ns3:jax_dept_id>RRI</ns3:jax_dept_id>
</ns3:dept_TT>
<ns3:dept_TT>
<ns3:dept_name>lab2</ns3:dept_name>
<ns3:jax_dept_id>RAFAC</ns3:jax_dept_id>
</ns3:dept_TT>
</ns0:dept_TT>
</ns0:uspInsertorUpdateDept>
Xml generated for the stored procedure in the VS
<ns0:uspInsertorUpdateDept xmlns:ns0="http://schemas.microsoft.com/Sql/2008/05/Procedures/dbo">
<ns0:dept_TT>
<ns1:dept_TT xmlns:ns1="http://schemas.microsoft.com/Sql/2008/05/Types/TableTypes/dbo">
<ns1:dept_name>dept_namedept_namedept_namedept_namedept_namedept_namedept_named</ns1:dept_name>
<ns1:jax_dept_id>jax_dept_idjax_dept_idjax_dept_i</ns1:jax_dept_id>
</ns1:dept_TT>
<ns1:dept_TT xmlns:ns1="http://schemas.microsoft.com/Sql/2008/05/Types/TableTypes/dbo">\
<ns1:dept_name>dept_namedept_namedept_namedept_namedept_namedept_namedept_named</ns1:dept_name>
<ns1:jax_dept_id>jax_dept_idjax_dept_idjax_dept_i</ns1:jax_dept_id>
</ns1:dept_TT>
<ns1:dept_TT xmlns:ns1="http://schemas.microsoft.com/Sql/2008/05/Types/TableTypes/dbo">
<ns1:dept_name>dept_namedept_namedept_namedept_namedept_namedept_namedept_named</ns1:dept_name>
<ns1:jax_dept_id>jax_dept_idjax_dept_idjax_dept_i</ns1:jax_dept_id>
</ns1:dept_TT>
</ns0:dept_TT>
</ns0:uspInsertorUpdateDept>
Not sure what am I missing here. Any help is greatly appreciated

Publish to SQL Azure fails with 'Cannot drop the external data source' message

I've got an SQL Project (.sqlproj) in my solution with target platform 'Microsoft Azure SQL Database V12'.
Recently I've added an external data source and several external tables targeting this data source.
ExternalCSVLists.sql file:
CREATE EXTERNAL DATA SOURCE [ExternalCSVLists] WITH
(
TYPE = RDBMS,
LOCATION = 'location.windows.net',
DATABASE_NAME = '$(CSVLists)',
CREDENTIAL = RemoteConnectionCredential
)
Example of external table (IntegerListContent.sql file)
CREATE EXTERNAL TABLE [WebApp].[IntegerListContent]
(
[ListId] INT,
[Value] int
)
WITH
(
DATA_SOURCE = [ExternalCSVLists]
)
First time publish went OK.
Now, when I publish again ( not having any changes done to either of external tables or data-sources), I receive the following error:
Dropping [ExternalCSVLists]...
(415,1): SQL72014: .Net SqlClient Data Provider: Msg 33165, Level 16, State 1, Line 1 Cannot drop the external data source 'ExternalCSVLists' because it is used by an external table.
I've inspected the publish script and noticed that it attempt to drop-and-create the external data source. The external tables are skipped ( which is probably OK since I didn't change them ).
So,
1) why does it yield a drop external data source statement when all such data sources are identical to those already published
2) why does it ignore the dependent external tables then?
My publish settings are pretty much default (none of the options in 'Drop' tab are checked ). Thanks!
I adapted the approaches above and have this in place in my DevOps release pipeline:
Run SQL script to drop all external objects in the target database, using an Azure SQL Database deployment task. This prevents the "unable to drop object" errors that can happen in a plain deployment.
declare #sql as nvarchar(max)
; with cmds as (
select
CONCAT('drop external table ' ,QUOTENAME(OBJECT_SCHEMA_NAME(t.object_id)) , '.' , QUOTENAME(OBJECT_NAME(t.object_id))) as Cmd
from sys.external_tables t
union all
select
'drop external data source ' + QUOTENAME(s.name)
from sys.external_data_sources s
)
select #sql= STRING_AGG(cmd,';')
from cmds
print #sql
if(len(#sql) > 0)
begin
exec sp_executesql #sql
end
Use an Azure SQL Database Deployment task to do a database deployment using a publish.xml profile that ignores all object types except external objects. This will recreate all the objects that were dropped in the previous step, but with the correct definitions.
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<IncludeCompositeObjects>True</IncludeCompositeObjects>
<TargetDatabaseName></TargetDatabaseName>
<DeployScriptFileName></DeployScriptFileName>
<BlockOnPossibleDataLoss>False</BlockOnPossibleDataLoss>
<GenerateSmartDefaults>True</GenerateSmartDefaults>
<DropObjectsNotInSource>True</DropObjectsNotInSource>
<DoNotDropPermissions>True</DoNotDropPermissions>
<DoNotDropRoleMembership>True</DoNotDropRoleMembership>
<DoNotDropUsers>True</DoNotDropUsers>
<IgnoreColumnOrder>True</IgnoreColumnOrder>
<ProfileVersionNumber>1</ProfileVersionNumber>
<ExcludeAggregates>True</ExcludeAggregates>
<ExcludeApplicationRoles>True</ExcludeApplicationRoles>
<ExcludeAssemblies>True</ExcludeAssemblies>
<ExcludeAsymmetricKeys>True</ExcludeAsymmetricKeys>
<ExcludeAudits>True</ExcludeAudits>
<ExcludeBrokerPriorities>True</ExcludeBrokerPriorities>
<ExcludeCertificates>True</ExcludeCertificates>
<ExcludeClrUserDefinedTypes>True</ExcludeClrUserDefinedTypes>
<ExcludeColumnEncryptionKeys>True</ExcludeColumnEncryptionKeys>
<ExcludeColumnMasterKeys>True</ExcludeColumnMasterKeys>
<ExcludeContracts>True</ExcludeContracts>
<ExcludeCryptographicProviders>True</ExcludeCryptographicProviders>
<ExcludeDatabaseAuditSpecifications>True</ExcludeDatabaseAuditSpecifications>
<ExcludeDatabaseRoles>True</ExcludeDatabaseRoles>
<ExcludeDatabaseTriggers>True</ExcludeDatabaseTriggers>
<ExcludeDefaults>True</ExcludeDefaults>
<ExcludeEndpoints>True</ExcludeEndpoints>
<ExcludeErrorMessages>True</ExcludeErrorMessages>
<ExcludeEventNotifications>True</ExcludeEventNotifications>
<ExcludeEventSessions>True</ExcludeEventSessions>
<IgnoreExtendedProperties>True</IgnoreExtendedProperties>
<ExcludeExternalDataSources>False</ExcludeExternalDataSources>
<ExcludeFileTables>True</ExcludeFileTables>
<ExcludeFilegroups>True</ExcludeFilegroups>
<ExcludeFullTextCatalogs>True</ExcludeFullTextCatalogs>
<ExcludeFullTextStoplists>True</ExcludeFullTextStoplists>
<ExcludeLinkedServerLogins>True</ExcludeLinkedServerLogins>
<ExcludeLinkedServers>True</ExcludeLinkedServers>
<ExcludeLogins>True</ExcludeLogins>
<ExcludePartitionFunctions>True</ExcludePartitionFunctions>
<ExcludeMessageTypes>True</ExcludeMessageTypes>
<ExcludePartitionSchemes>True</ExcludePartitionSchemes>
<IgnorePermissions>True</IgnorePermissions>
<ExcludeQueues>True</ExcludeQueues>
<ExcludeRemoteServiceBindings>True</ExcludeRemoteServiceBindings>
<IgnoreRoleMembership>True</IgnoreRoleMembership>
<ExcludeRoutes>True</ExcludeRoutes>
<ExcludeRules>True</ExcludeRules>
<ExcludeScalarValuedFunctions>True</ExcludeScalarValuedFunctions>
<ExcludeSearchPropertyLists>True</ExcludeSearchPropertyLists>
<ExcludeSecurityPolicies>True</ExcludeSecurityPolicies>
<ExcludeSequences>True</ExcludeSequences>
<ExcludeServerAuditSpecifications>True</ExcludeServerAuditSpecifications>
<ExcludeServerRoleMembership>True</ExcludeServerRoleMembership>
<ExcludeServerRoles>True</ExcludeServerRoles>
<ExcludeServerTriggers>True</ExcludeServerTriggers>
<ExcludeServices>True</ExcludeServices>
<ExcludeSignatures>True</ExcludeSignatures>
<ExcludeStoredProcedures>True</ExcludeStoredProcedures>
<ExcludeSymmetricKeys>True</ExcludeSymmetricKeys>
<ExcludeSynonyms>True</ExcludeSynonyms>
<ExcludeTableValuedFunctions>True</ExcludeTableValuedFunctions>
<ExcludeTables>True</ExcludeTables>
<ExcludeUserDefinedDataTypes>True</ExcludeUserDefinedDataTypes>
<ExcludeUserDefinedTableTypes>True</ExcludeUserDefinedTableTypes>
<ExcludeUsers>True</ExcludeUsers>
<ExcludeViews>True</ExcludeViews>
<ExcludeXmlSchemaCollections>True</ExcludeXmlSchemaCollections>
<ExcludeCredentials>True</ExcludeCredentials>
</PropertyGroup>
</Project>
Use another Azure SQL Database Deployment task to do a database deployment using a publish.xml profile that ignores all external object types.
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<IncludeCompositeObjects>True</IncludeCompositeObjects>
<TargetDatabaseName></TargetDatabaseName>
<DeployScriptFileName></DeployScriptFileName>
<BlockOnPossibleDataLoss>False</BlockOnPossibleDataLoss>
<GenerateSmartDefaults>True</GenerateSmartDefaults>
<DropObjectsNotInSource>True</DropObjectsNotInSource>
<DoNotDropPermissions>True</DoNotDropPermissions>
<DoNotDropRoleMembership>True</DoNotDropRoleMembership>
<DoNotDropUsers>True</DoNotDropUsers>
<IgnoreColumnOrder>True</IgnoreColumnOrder>
<ProfileVersionNumber>1</ProfileVersionNumber>
<ExcludeCredentials>True</ExcludeCredentials>
<ExcludeDatabaseScopedCredentials>True</ExcludeDatabaseScopedCredentials>
<ExcludeExternalTables>True</ExcludeExternalTables>
<ExcludeExternalFileFormats>True</ExcludeExternalFileFormats>
<ExcludeExternalDataSources>True</ExcludeExternalDataSources>
</PropertyGroup>
</Project>
I hit the same issue; and unfortunately I could not figure out why this problem was created in the first place.
But the work around was to introduce a pre-deployment step that dropped ALL
Tables AND
Views
That referenced the External Data Source... I would have expected the DACPAC to perform this on its own; but I suppose we live in a non-perfect world.
I have also this problem. As a workaround you can also use: /p:DoNotDropObjectTypes=ExternalDataSources
But it works only if you have no changes in your external data source.
I opened a feedback case on microsoft. If you like you can support the case.

The execution of a SP in SSIS returns nothing

Until now I've been looking for a possible solution to the execution of a sp from SSIS, but anything seems to work. I´ve got a sp:
CREATE PROCEDURE [DBO].[SPIDENTIFIERS] #IDENT NVARCHAR(MAX) OUTPUT
What I need is to save the result in a variable that I've created in SSIS.
This is the configuration that I used to try to do it.
In the parameter set section I have also used the Direction as Output or ReturnValue but I received a error message. Just to try I put a Script Task to chek the value, but as you can see this is empty.
With the Direction Ouput or ReturnValue I've got this:
[Execute SQL Task] Error: Executing the query "EXECUTE spIdentifiers ? OUTPUT;" failed with the following error:
"El valor no está dentro del intervalo esperado.".
Possible failure reasons: Problems with the query, "ResultSet" property not set correctly,
parameters not set correctly, or connection not established correctly.
What am I missing in the configuration of the task?.
I looked for an answer in this post. But nothing seems to work
How do you call a Stored Procedure in SSIS?
SSIS Stored Procedure Call
Thanks in advance.
Your parameter should not be named, as #gerald Davis has indicated. For a connection manager of OLEDB type, it should be ordinal based, thus 0
Here's my sample package and you can see that my variable #[User::MyVariables] is populated with a lot of Xs
Here's my proc definition
IF NOT EXISTS
(
SELECT
*
FROM
sys.procedures AS P
WHERE
P.name = N'SPIDENTIFIERS'
)
BEGIN
EXECUTE sys.sp_executesql N'CREATE PROC dbo.spidentifiers AS SELECT ''stub version, to be replaced''';
END
GO
ALTER PROCEDURE [DBO].[SPIDENTIFIERS]
(
#IDENT NVARCHAR(MAX) OUTPUT
)
AS
BEGIN
SET NOCOUNT ON;
SET #IDENT = REPLICATE(CAST(N'X' AS nvarchar(MAX)), 4001);
-- Uncomment this to watch the fireworks
--SET #IDENT = REPLICATE(CAST(N'X' AS nvarchar(MAX)), 4001);
END
Biml
I'm a big fan of using Biml, the Business Intelligence Markup Language, to describe my solutions as it allows the reader to recreate exactly the solution I describe without all those pesky mouse clicks.
Download BIDS Helper and install or unzip
Add a new biml file to your SSIS project
Fix the third line's ConnectionString to point to a valid server and database. Mine references localhost\dev2014 and tempdb
Right click on the saved biml file and generate package
Take your well deserved Biml break
Biml code follows
<Biml xmlns="http://schemas.varigence.com/biml.xsd">
<Connections>
<OleDbConnection Name="tempdb" ConnectionString="Provider=SQLNCLI11.1;Server=localhost\dev2014;Initial Catalog=tempdb;Integrated Security=SSPI;" />
</Connections>
<Packages>
<Package Name="so_30460630" ConstraintMode="Linear">
<Variables>
<Variable DataType="String" Name="MyVariables">0</Variable>
</Variables>
<Tasks>
<ExecuteSQL
ConnectionName="tempdb"
Name="SQL Ensure Objects Exist">
<DirectInput>
<![CDATA[IF NOT EXISTS
(
SELECT
*
FROM
sys.procedures AS P
WHERE
P.name = N'SPIDENTIFIERS'
)
BEGIN
EXECUTE sys.sp_executesql N'CREATE PROC dbo.spidentifiers AS SELECT ''stub version, to be replaced''';
END
GO
ALTER PROCEDURE [DBO].[SPIDENTIFIERS]
(
#IDENT NVARCHAR(MAX) OUTPUT
)
AS
BEGIN
SET NOCOUNT ON;
SET #IDENT = REPLICATE(CAST(N'X' AS nvarchar(MAX)), 4001);
END
]]>
</DirectInput>
</ExecuteSQL>
<ExecuteSQL
ConnectionName="tempdb"
Name="SQL Using an OUTPUT parameter">
<DirectInput>EXECUTE dbo.SPIDENTIFIERS ? OUTPUT;</DirectInput>
<Parameters>
<Parameter DataType="String" VariableName="User.MyVariables" Name="0" Direction="Output" Length="-1" />
</Parameters>
</ExecuteSQL>
<ExecuteSQL
ConnectionName="tempdb"
Name="SQL Breakpoint">
<DirectInput>SELECT NULL AS nothing;</DirectInput>
</ExecuteSQL>
</Tasks>
</Package>
</Packages>
</Biml>
Your stored procedure parameter is OUTPUT but your SSIS package defines it as INPUT. Depending on the application, RETURNVALUE could also be used but from the syntax of your SP it is using an Output Parameter not a Return Value.
Verify the User:Id variable has the correct datatype. Try executing the SP in SSMS manually to verify that it runs without error and returns the expected result.
Also I think you are mixing OLEDB and ADO.NET syntax.
If using an OLEDB Data connection then you use the ? parameters in the query and the Parameter names must be "Parameter0 (and Parameter1, etc if more than 1)". Note: parameter names are zero indexed. In SP with more than 1 parameter the correct order is required.
If using an ADO.NET DataConnection then the query is just the named of the stored procedure, IsStoredProcedure=True, and the Parameter names matches the name of the parameter in the SP.
From your screenshots you currently are using named parameters and OLDEDB ? syntax. I don't believe that is ever valid. It is one or the other depending on the connection type.
UserID needs to be in the readwritevariable section, not the read section, so that you allow the task to write into the variable.
parameter direction should be "output" since you are passing it out of your task not into it.
You need to keep the sql statement as "EXEC SPIDENTIFIERS ? OUTPUT**
direction of variable should be Output in parameter mapping tab and "Parameter Name" should be exactly same as of input parameter defined in stored procedure or you can just use 0 instead of giving the actual name.

xp_regread() returned error 5, 'Access is denied.'

I'm running the SQL Server Copy Database Wizard.
Of note is that the Operator is NT AUTHORITY\SYSTEM, which I thought should have the authority to run whatever it wants.
How can we grant sufficient privileges to NT AUTHORITY\SYSTEM? I have already tried:
GRANT EXECUTE ON xp_regread TO public
GRANT EXECUTE ON xp_regread TO [NT AUTHORITY\SYSTEM]
And running the following shows that it worked.
SELECT
grantee_principal.name AS [Grantee]
, prmssn.permission_name
FROM
sys.all_objects AS xproc
INNER JOIN sys.database_permissions AS prmssn ON prmssn.major_id=xproc.object_id AND prmssn.minor_id=0 AND prmssn.class=1
INNER JOIN sys.database_principals AS grantee_principal ON grantee_principal.principal_id = prmssn.grantee_principal_id
WHERE
(xproc.type='X')and(xproc.name=N'xp_regread' and SCHEMA_NAME(xproc.schema_id)=N'sys')
Output:
Grantee permission_name
public EXECUTE
NT AUTHORITY\SYSTEM EXECUTE
The following error occurs:
Event Name: OnError
Message: An exception occurred while executing a Transact-SQL statement or batch.
StackTrace: at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteReader(String sqlCommand, SqlCommand& command)
at Microsoft.SqlServer.Management.Smo.ExecuteSql.GetDataReader(String query, SqlCommand& command)
at Microsoft.SqlServer.Management.Smo.DataProvider.SetConnectionAndQuery(ExecuteSql execSql, String query)
at Microsoft.SqlServer.Management.Smo.ExecuteSql.GetDataProvider(StringCollection query, Object con, StatementBuilder sb, RetriveMode rm)
at Microsoft.SqlServer.Management.Smo.SqlObjectBase.FillData(ResultType resultType, StringCollection sql, Object connectionInfo, StatementBuilder sb)
at Microsoft.SqlServer.Management.Smo.SqlObjectBase.FillDataWithUseFailure(SqlEnumResult sqlresult, ResultType resultType)
at Microsoft.SqlServer.Management.Smo.SqlObjectBase.BuildResult(EnumResult result)
at Microsoft.SqlServer.Management.Smo.SqlServer.GetData(EnumResult erParent)
at Microsoft.SqlServer.Management.Sdk.Sfc.Environment.GetData()
at Microsoft.SqlServer.Management.Sdk.Sfc.Environment.GetData(Request req, Object ci)
at Microsoft.SqlServer.Management.Sdk.Sfc.Enumerator.GetData(Object connectionInfo, Request request)
at Microsoft.SqlServer.Management.Smo.ExecutionManager.GetEnumeratorDataReader(Request req)
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.GetInitDataReader(String[] fields, OrderBy[] orderby)
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.ImplInitialize(String[] fields, OrderBy[] orderby)
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.Initialize(Boolean allProperties)
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.OnPropertyMissing(String propname, Boolean useDefaultValue)
at Microsoft.SqlServer.Management.Smo.PropertyCollection.RetrieveProperty(Int32 index, Boolean useDefaultOnMissingValue)
at Microsoft.SqlServer.Management.Smo.PropertyCollection.GetValueWithNullReplacement(String propertyName, Boolean throwOnNullValue, Boolean useDefaultOnMissingValue)
at Microsoft.SqlServer.Management.Smo.Server.get_InstanceName()
at Microsoft.SqlServer.Dts.Tasks.TransferObjectsTask.MappedLogin.RefreshData()
at Microsoft.SqlServer.Dts.Tasks.TransferObjectsTask.MappedLogin.CheckDirty()
at Microsoft.SqlServer.Dts.Tasks.TransferObjectsTask.TransferObjectsTask.GetDatabaseLogins()
at Microsoft.SqlServer.Dts.Tasks.TransferObjectsTask.TransferObjectsTask.UpdateObjectsToCopy()
InnerException-->xp_regread() returned error 5, 'Access is denied.'
xp_regread() returned error 5, 'Access is denied.'
xp_regread() returned error 5, 'Access is denied.'
StackTrace: at Microsoft.SqlServer.Management.Common.ConnectionManager.ExecuteTSql(ExecuteTSqlAction action, Object execObject, DataSet fillDataSet, Boolean catchException)
at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteReader(String sqlCommand, SqlCommand& command)
Operator: NT AUTHORITY\SYSTEM
Source Name: SQLSERVER2008R2_Transfer Objects Task
Source ID: {9D0562F4-FCC9-498D-A2A9-FC9E5F3B681B}
Execution ID: {23FF505D-00D3-4F84-8B9D-D9EC962C78D2}
Start Time: 2015-04-17 7:23:24 PM
End Time: 2015-04-17 7:23:24 PM
Data Code: 0
This is the tool we need to use, because we don't have access to the remote server, and because the Import-Export Wizard failed.
You might need to add the account to the sysadmin server role, which allows a member to perform every activity.
For 2008r2, execute this command:
EXEC sp_addsrvrolemember 'NT AUTHORITY\SYSTEM', 'sysadmin';
This is a common error encountered when attempting to update the registry from SQL Server, and there are some weird and non-obvious pathing issues in newer versions such as SQL Server 2017.
The error is not due to security within SQL Server, but instead Windows security related to the permissions on the registry keys as relates to the users under which specific SQL Server processes are running.
For instance, to execute MSSQL related registry commands from SQL Server, the system group NETWORKSERVICE needs full control on the relevant registry path. This is because SQL Agent (by default) runs as a user in that system group.
For SQL Server settings, the Registry path is:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server
As an example, the command in SQL Server to set the log file size limit to be 1024 KB is as follows:
USE [master]
GO
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE',
N'SOFTWARE\Microsoft\Microsoft SQL Server\MSSQLServer',
N'ErrorLogSizeInKb', REG_DWORD, 1024
GO
Also note the truncated path above. The actual full registry path (for SQL2017) is as follows:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQLServer
The xp_instance_regwrite SQL Server command automatically injects the version key into the path. For SQL Server 2017 that key is MSSQL14.MSSQLSERVER.

Resources