Error while updating Database with mssql_query - sql-server

I'm using mssql_query to connect to an existing SQL Server 2008 Database.
SELECT querys are ok, but when I run UPDATE querys like the following:
mssql_query("UPDATE TABLENAME SET fieldname = 1 WHERE Pk = '".$pk."'");
I get this error:
UPDATE failed because the following SET options have incorrect
settings: 'ANSI_NULLS, QUOTED_IDENTIFIER, CONCAT_NULL_YIELDS_NULL,
ANSI_WARNINGS, ANSI_PADDING'. Verify that SET options are correct for
use with indexed views and/or indexes on computed columns and/or
filtered indexes and/or query notifications and/or XML data type
methods and/or spatial index operations. (severity 16)
Here is my connection code to Database:
$server = 'SRVSQL';
// Connect to MSSQL
$link = mssql_connect($server, 'xx', 'xxxxxx');
if (!$link) {
die('Something went wrong while connecting to MSSQL');
}
$conn = mssql_select_db('xxxxxxx',$link);

You might have to explicitly change the settings by turning the settings on. You can do so by issuing the following query prior to the UPDATE statement:
SET
ANSI_NULLS,
QUOTED_IDENTIFIER,
CONCAT_NULL_YIELDS_NULL,
ANSI_WARNINGS,
ANSI_PADDING
ON;
Should there be additional settings yielding errors, those might have to be changed as well.
See also: ANSWER: UPDATE failed because the following SET options have incorrect settings: 'ANSI_NULLS, QUOTED_IDENTIFIER'

Related

SQL Server Distributed queries with Teradata

I am trying to get distributed queries to run on SQL Server 2012 with a linked server to Teradata.
Connection works fine and query returns quickly if I pass the where clause into the remote SQL using openquery e.g.
select *
from openquery(td, 'select * from lib.purchases where z_PO = ''123456''')
However the below does not run as expected: SQL Server loads the entire table and performs a local filter:
select *
from openquery(td, 'select * from lib.purchases') where z_PO = '123456'
The source table has 100M records.
Obviously index play no role here as query runs just fine on TD side.
What I have tried:
sp_configure 'Ad Hoc Distributed Queries', 1
set Collation Compatible" = True on the linked server properties
Instead of 2, set Collation Name = Latin1_BIN to match (closely?) TD character set (ASCII).
Not sure collation is the issue as I get same result when filtering on numeric fields.
Somehow the so-called query optimizer in SQL Server does not push simple filtering down to the remote server.
Is this the ODBC driver's fault (using 16.10) - a setting, a bug? SQL Server 2012 (v11.0.6248.0) setting I am missing (or path req'd)?
Below is the OLEDB for ODBC properties that I capture in SQL Profiler:
<ProviderInformation>
<Provider>MSDASQL</Provider>
<LinkedServer>td</LinkedServer>
<ProviderCapabilitiesAndSettings>
<Ansi92EntrySupport>0</Ansi92EntrySupport>
<ODBCCoreSupport>1</ODBCCoreSupport>
<ODBCMinimumSupport>1</ODBCMinimumSupport>
<SimpleGrammarSupport>0</SimpleGrammarSupport>
<AnsiLikeSupport>0</AnsiLikeSupport>
<SQLLikeSupport>1</SQLLikeSupport>
<DateLiteralsSupport>0</DateLiteralsSupport>
<GroupBySupport>0</GroupBySupport>
<InnerJoinSupport>0</InnerJoinSupport>
<SubqueriesSupport>0</SubqueriesSupport>
<SimpleUpdatesSupport>0</SimpleUpdatesSupport>
<HistogramsSupport>0</HistogramsSupport>
<ColumnLevelCollationSupport>0</ColumnLevelCollationSupport>
<ConnectionSharingSupport>0</ConnectionSharingSupport>
<MultipleActiveRowsetsSupport>0</MultipleActiveRowsetsSupport>
<MultipleResultsSupport>1</MultipleResultsSupport>
<AllowLimitingRowsReturned>1</AllowLimitingRowsReturned>
<NullConcatenationYieldsNull>0</NullConcatenationYieldsNull>
<StructuredStorageAccessToLargeObjects>1</StructuredStorageAccessToLargeObjects>
<MultipleConcurrentLargeObjectSupport>0</MultipleConcurrentLargeObjectSupport>
<DynamicParametersSupport>1</DynamicParametersSupport>
<NestedQueriesSupport>1</NestedQueriesSupport>
<IndicesAvailableAsAccessPath>0</IndicesAvailableAsAccessPath>
<AllowDataAccessByReference>1</AllowDataAccessByReference>
<RowsetChangesAreVisible>0</RowsetChangesAreVisible>
<RowsetSupportsAppendOnly>0</RowsetSupportsAppendOnly>
<UseLevelZeroOledbInterfacesOnly>0</UseLevelZeroOledbInterfacesOnly>
<RowsetUpdatability>1</RowsetUpdatability>
<AsynchronousRowsetProcessingSupport>0</AsynchronousRowsetProcessingSupport>
<DataSourceUnicodeLocaleId>0</DataSourceUnicodeLocaleId>
<DataSourceUnicodeComparisonStyle>0</DataSourceUnicodeComparisonStyle>
<DataSourceCollationComparisonFlags>0</DataSourceCollationComparisonFlags>
<DataSourceCharacterset></DataSourceCharacterset>
<DataSourceSortOrder></DataSourceSortOrder>
<DataSourceNullCollationOrder>4</DataSourceNullCollationOrder>
<CurrentDbCollationSameAsDefaultRemoteDbCollation>0</CurrentDbCollationSameAsDefaultRemoteDbCollation>
<UnicodeLiteralSupport>0</UnicodeLiteralSupport>
<UnicodeLiteralPrefix></UnicodeLiteralPrefix>
<UnicodeLiteralSuffix></UnicodeLiteralSuffix>
<DateLiteralPrefix></DateLiteralPrefix>
<DateLiteralSuffix></DateLiteralSuffix>
<ObjectNameConstructionFlags>54</ObjectNameConstructionFlags>
<SchemaSeparator>.</SchemaSeparator>
<CatalogSeparator>.</CatalogSeparator>
<QuoteSeparator>"</QuoteSeparator>
<BitRemoting>0</BitRemoting>
<UnicodeLiterals>0</UnicodeLiterals>
<ProviderOledbVersion>131072</ProviderOledbVersion>
<HalloweenProtectionNeeded>1</HalloweenProtectionNeeded>
<RowsetUsableAcrossThreads>0</RowsetUsableAcrossThreads>
<ObjectNameIsSinglePart>0</ObjectNameIsSinglePart>
<Cardinality>-1</Cardinality>
<BookmarkSupport>0</BookmarkSupport>
<BookmarksReusable>0</BookmarksReusable>
<TableFlags>0</TableFlags>
</ProviderCapabilitiesAndSettings>
and here the details of the column in the filter:
DBCOLUMNINFO>
<pwszName>z_PO</pwszName>
<pTypeInfo>0x0000000000000000</pTypeInfo>
<iOrdinal>53</iOrdinal>
<dwFlags>120</dwFlags>
<ulColumnSize>10</ulColumnSize>
<wType>129</wType>
<bPrecision>255</bPrecision>
<bScale>255</bScale>
<DBID>
<eKind>DBKIND_NAME</eKind>
<uName.pwszName>z_PO</uName.pwszName>
</DBID>
</DBCOLUMNINFO>
As a FYI, the context is wrapping the openquery, joined with local data, into a SQL Server view, which is the only thing users would see - from there, they can apply any filter (WHERE) within PowerQuery (XL) or PowerBI. A way to circumvent the lack of DirectQuery support through ODBC.

Updating SQL Server table with GEOGRAPHY column in Django

I have a Django 1.8.3 application that I'm connecting to SQL Server Enterprise 2012 as one of the databases. I am using django-pyodbc-azure==1.8.3.0 and my connection looks like this:
'sql_server': {
'ENGINE': 'sql_server.pyodbc',
'NAME': 'mydb',
'USER': 'myuser',
'PASSWORD': 'mypass',
'HOST': '173.1.1.1',
'PORT': 1433,
'OPTIONS': {
'host_is_server': True,
}
},
I have a column in a table in the database that was created as such:
ALTER TABLE mytable ADD geo AS GEOGRAPHY::Point (
latitude
,longitude
,4326
) persisted;
CREATE spatial INDEX SI_mytable__geo ON mytable (geo)
When trying to update any column in this table via the Django admin, I receive this error:
('42000', "[42000] [FreeTDS][SQL Server]UPDATE failed because the
following SET options have incorrect settings: 'ANSI_NULLS,
QUOTED_IDENTIFIER, CONCAT_NULL_YIELDS_NULL, ANSI_WARNINGS,
ANSI_PADDING'. Verify that SET options are correct for use with
indexed views and/or indexes on computed columns and/or filtered
indexes and/or query notifications and/or XML data type methods and/or
spatial index operations. (1934) (SQLExecDirectW)")
My database currently has SET options like this:
SELECT
is_ansi_nulls_on,
is_ansi_padding_on,
is_ansi_warnings_on,
is_arithabort_on,
is_concat_null_yields_null_on,
is_numeric_roundabort_on,
is_quoted_identifier_on
FROM sys.databases
is_ansi_nulls_on is_ansi_padding_on is_ansi_warnings_on is_arithabort_on is_concat_null_yields_null_on is_numeric_roundabort_on is_quoted_identifier_on
0 0 0 0 0 0 0
I only receive this error in production and not when running in development on my laptop. I understand that I need to correctly update the SET options, per the error and this answer: https://stackoverflow.com/a/9235638/1753891
How can I tell django-pyodbc-azure to send the correct SET options prior to updating this table?
Or do I need to update the options on the database itself and, if so, are they any potential pitfalls to watch out for if I change these SET options?
I ending up changing the SET options in the model's save method and this is working for now.
class MyModel(models.Model):
# Model fields here
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
cursor = connections['sql_server'].cursor()
cursor.execute("""SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_WARNINGS ON
SET ANSI_PADDING ON""")
cursor.close()
super(MyModel, self).save(force_insert, force_update, using, update_fields)

How to update conflict resolver when upgrading from SQL-Server 2005 to SQL-Server 2008

We have recently upgraded from SQL Server 2005 to SQL Server 2008 (R2, SP1). This upgrade included some publications, where all tables are published with a default conflict resolver based on the "later wins" principle. Its smart name is 'Microsoft SQL Server DATETIME (Later Wins) Conflict Resolver', and the corresponding dll file is ssrmax.dll.
As you all know, once a table is published with a conflict resolver, the same conflict resolver must be used in all later publications using this table. Fair enough, but, when adding previously published tables to new publications, and specifying the very same conflict resolver to be used for this table, we are getting an error message:
use [myDb]
exec sp_addmergearticle
#publication = N'myDb_Pub',
#article = N'Tbl_blablabla',
#source_owner = N'dbo',
#source_object = N'Tbl_blablabla',
#type = N'table',
#description = N'',
#creation_script = N'',
#pre_creation_cmd = N'drop',
#schema_option = 0x000000000C034FD1,
#identityrangemanagementoption = N'none',
#destination_owner = N'dbo',
#force_reinit_subscription = 1,
#column_tracking = N'false',
#article_resolver = N'Microsoft SQL Server DATETIME (Later Wins) Conflict Resolver',
#subset_filterclause = N'',
#resolver_info = N'ddmaj',
#vertical_partition = N'false',
#verify_resolver_signature = 0,
#allow_interactive_resolver = N'false',
#fast_multicol_updateproc = N'true',
#check_permissions = 0,
#subscriber_upload_options = 0,
#delete_tracking = N'true',
#compensate_for_errors = N'false',
#stream_blob_columns = N'false',
#partition_options = 0
GO
And this is the error we get:
The article '...' already exists in another publication with a different article resolver.
By trying to understand how the same conflict resolver is not considered by the machine as 'the same conflict resolver', I discovered that there were two conflict resolvers with the same name, different versions, in the registry:
the 2005 version:
file ssrmax.dll,
version 2005.90.4035.0,
cls_id D604B4B5-686B-4304-9613-C4F82B527B10
the 2008 version:
file ssrmax.dll,
version 2009.100.2500.0,
cls_id 77209412-47CF-49AF-A347-DCF7EE481277
And I checked that our 2008 server is considering the second one as the 'available custom resolver' (I got this by running sp_enumcustomresolvers). The problem is that both references are available in the registry, so I guess that old publications do refer to the 2005 version, while new publications try to refere to the 2008 version, which is indeed different from the previous one.
So the question is: how can I have the server consider only one of these 2 versions, and this (of course) without having to drop and recreate the existing publications (which would turn our life into hell for the next 2 weeks).
Well .. so nobody got an answer. But I think I (finally) got it. Guess what... it is somewhere in the metamodel (as usual)!
When adding an item to the subscription, the new conflict resolver references to be used by the stored procedure come from the [distribution].[MSmerge_articleresolver] table
But, for existing subscriptions, previous conflict resolver references are stored in the system tables of the publishing database, ie [sysmergearticles], [sysmergeextendedarticlesview], and [sysmergepartitioninfoview]
So we have on one side an item initialy published with SQLSERVER 2005, where the publication references the 2005 conflict resolver, as per the publishing database metamodel. On the other side, the machine will attempt to add the same item to a new publication, this time with a default reference to the conflict resolver available in the distibution database, which is indeed different from the 2005 one ....
To illustrate this, you can check the following
USE distribution
go
SELECT article_resolver, resolver_clsid
FROM [MSmerge_articleresolver] WHERE article_resolver like '%Later Wins%'
GO
Then,
USE myPublicationDatabase
go
SELECT article_resolver, resolver_clsid
FROM [sysmergearticles] WHERE article_resolver like '%Later Wins%'
GO
SELECT article_resolver, resolver_clsid
FROM [sysmergeextendedarticlesview] WHERE article_resolver like '%Later Wins%'
GO
SELECT article_resolver, resolver_clsid
FROM [sysmergepartitioninfoview] WHERE article_resolver like '%Later Wins%'
GO
So it seems that I should update either the references in the distribution database or the references in the publication database. Let's give it a try!
Thanks, had something similar on a re-publisher where the subscriber article had a CLSID that made no sense on the server (looked with Regedit) but when trying to add the article to a publication would produce said error.
Updated the resolver_clsid field of sysMergeArticles table for the subscribed article with the clisd it was trying to get
{
declare #resolver_clsid nvarchar(50)
exec sys.sp_lookupcustomresolver N'Microsoft SQL Server DATETIME (Earlier Wins) Conflict Resolver', #resolver_clsid OUTPUT
select #resolver_clsid
}
and could then add the article

SqlDependency causes error in other application

I have a project where I need to monitor changes in a 3rd party database.
SqlDependency seem like a good solution but it causes the following error in the 3rd party application.
INSERT failed because the following SET options have incorrect
settings: 'ANSI_NULLS, QUOTED_IDENTIFIER, ANSI_PADDING'. Verify that
SET options are correct for use with indexed views and/or indexes on
computed columns and/or filtered indexes and/or query notifications
and/or XML data type methods and/or spatial index operations.
(The application works fine when my test program below is not running)
What SET options does this refer to?
The only set operation I have done is ALTER DATABASE TestDb SET ENABLE_BROKER to enable notifications.
I also did:
CREATE QUEUE ContactChangeMessages;
CREATE SERVICE ContactChangeNotifications
ON QUEUE ContactChangeMessages
([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification]);
Here is my Linqpad test code which works fine if I insert/update/delete records in management studio.
void Main() {
const string cs = "Data Source=.;Initial Catalog=TestDb;Trusted_Connection=True";
var are = new AutoResetEvent(false);
using (var connection = new SqlConnection(cs)) {
connection.Open();
SqlDependency.Start(cs);
using (var cmd = new SqlCommand()) {
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT orderNo FROM dbo.Orders WHERE ProductNo = '111'";
var dep = new SqlDependency(cmd, null, 60);
dep.OnChange += (s,e) => {
Console.WriteLine(e.Info);
are.Set();
};
using (var reader = cmd.ExecuteReader()) {
while (reader.Read()) {
}
}
are.WaitOne();
SqlDependency.Stop(cs);
}
}
}
I do not know, and can not change, how the 3rd part app connects to the database. I can run the sql profiler if more information is required.
It refers exactly to the SET options mentioned in the error message:
SET options have incorrect settings: 'ANSI_NULLS, QUOTED_IDENTIFIER,
ANSI_PADDING'.
The correct settings, along with other restrictions, are described in Creating a Query for Notification:
When a SELECT statement is executed under a notification request, the
connection that submits the request must have the options for the
connection set as follows:
ANSI_NULLS ON
ANSI_PADDING ON
ANSI_WARNINGS ON
CONCAT_NULL_YIELDS_NULL ON
QUOTED_IDENTIFIER ON
NUMERIC_ROUNDABORT OFF
ARITHABORT ON
Note Note
Setting ANSI_WARNINGS to ON implicitly sets ARITHABORT to ON when the
database compatibility level is set to 90. If the database
compatibility level is set to 80 or earlier, the ARITHABORT option
must explicitly be set to ON.
These settings are affected by:
the current database settings, which can be viewed in sys.databases
the session settings, which can be viewed in sys.dm_exec_sessions
by procedure/trigger create settings, which can be viewed using OBJECTPROPERTY().
You need to find which property from the ones mentioned in the error message is non-conforming and why (probably is a database setting). Most likely is a 80 compatibility level set on the database.
Update. Nevermind that, you say that you can successfully create a query notification but then the application itself fails. The application must be explicitly setting one of these settings OFF on it's connection (you can validate by inspecting sys.dm_exec_sessions). You must contact the application vendor, seems like she is very explicitly (albeit probably unintentionally) making his application incompatible with query notifications.

SQL Server transactions - whole db locked?

I have a problem on specific SQL Server 2008 customer installation. I wrote the code below to simulate the problem which happens in more complex system. There are two connections (each one with own transaction) opened and each connection modifies a table. Modified tables do not relate to each other. On development platform and other existing customer installations the code works fine. Only at one specific customer we have a problem that the second update in nested transaction hangs. I could make a workaround by moving the first update after commit of nested transaction.
I assume in that specific installation the db is configured to lock down the whole db when a transaction is started. But using DBCC useroptions results in very similar output on systems where the code works and this one.
How can I identify what's wrong here ?
Here's DBCC useroptions output from the problematic DB (SQL Server 2008) and my simplified test code:
textsize 2147483647
language Deutsch
dateformat dmy
datefirst 1
lock_timeout -1
quoted_identifier SET
arithabort SET
ansi_null_dflt_on SET
ansi_warnings SET
ansi_padding SET
ansi_nulls SET
concat_null_yields_null SET
isolation level read committed
DbCommand command1 =null, command2 = null;
try
{
const string cs = "Provider=SQLOLEDB.1;...";
// open command and a transaction with default isolation level
command1 = DbAccessFactory.CreateInitialzedCommand("System.Data.OleDb", cs, true);
// select something
command1.CommandText = "select * from plannerOrderHeaders where ...";
DataSet ds = BusinessCasesHelper.Fill(command1, null, "plannerOrderHeaders");
// make some changes in the table
...
// update the table in DB
BusinessCasesHelper.Update(command1, ds, true);
// open command and a transaction with default isolation level on the same CS as command1
command2 = DbAccessFactory.CreateInitialzedCommand("System.Data.OleDb", cs, true);
// select something
command2.CommandText = "select * from mdOmOrders where ...";
ds = BusinessCasesHelper.Fill(command2, null, "mdOmOrders");
// make some changes
...
// update the db
BusinessCasesHelper.Update(command2, ds, true);
command2.Transaction.Commit();
cmd2Commited = true;
command1.Transaction.Commit();
}
catch (Exception e) {...}
And why do you use ""Provider=SQLOLEDB.1" to access MS SQL Server?
And why do you commit instead of closing and disposing?
I can only guess how the mentioned BusinessCasesHelper, DbAccessFactory, etc. are implemented.
But your question implies that your consider your snippet opening transaction inside another transaction in the same context (i.e. on one connection) while I see that they are probably opening two connections which are not being disposed.

Resources