SQL Server: The ALTER TABLE statement conflicted with the CHECK constraint - sql-server

I am confused about why this doesn't work:
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE dbo.Accounts ADD CONSTRAINT
CK_client_not_null CHECK (site <> 'LWOP' and client is not null)
GO
ALTER TABLE dbo.Accounts SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
will throw this error:
Msg 547, Level 16, State 0, Line 13
The ALTER TABLE statement conflicted with the CHECK constraint "CK_client_not_null". The conflict occurred in database "ss", table "dbo.Accounts".
Msg 3902, Level 16, State 1, Line 18
The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.
but when I run the following:
select *
from Accounts
where site = 'LWOP' or client is null
I am getting only that row that can have client as null.
What am I missing here?
Once again: I want to make a constraint that will restrict null values on client column ONLY if site <> 'LWOP', so how to do it?
Thanks,
Dejan

I found the solution already:
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE dbo.Accounts ADD CONSTRAINT
CK_client_not_null CHECK (site <> 'LWOP' and client is not null OR site = 'LWOP')
GO
ALTER TABLE dbo.Accounts SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
site <> 'LWOP' and client is not null OR site = 'LWOP' - that covers all situations for check to work.

Related

Heterogeneous queries require the ANSI_NULLS and ANSI_WARNINGS - Trigger dealing with linked server

Upon trying to insert into table via app, I receive following error message.
Heterogeneous queries require the ANSI_NULLS and ANSI_WARNINGS options to be set for the connection.
Neither ANSI_NULLS ON nor ANSI_WARNINGS ON did help...
SET ANSI_NULLS ON
GO
SET ANSI_WARNINGS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[BenRef_UPDATE]
ON [dbo].[ITRAEN]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON
IF UPDATE(poz2)
CREATE TABLE storeBenRef(
BeneficiaryRef VARCHAR(30),
Partija VARCHAR(30) collate Serbian_Latin_100_CI_AS,
Datum DATETIME
);
INSERT INTO storeBenRef ( BeneficiaryRef, Partija, Datum )
SELECT i.poz2, i.PARTIJA,i.DOTVORANJE
FROM inserted i
INNER JOIN deleted d
ON i.PARTIJA = d.PARTIJA;
SET ANSI_NULLS ON
SET ANSI_WARNINGS ON
UPDATE [EXPSRV1].[OPR].[protected].[TransferServiceArrangement]
SET PaymentDetailsBeneficiaryReferenceNumber = tmp.BeneficiaryRef
FROM storeBenRef tmp
INNER JOIN [EXPSRV1].[OPR].[protected].[TransferServiceArrangement]
trsa
ON trsa.PaymentDetailsPayerAccountNumber = tmp.partija
WHERE trsa.FirstPaymentDate = tmp.Datum
DROP TABLE dbo.storeBenRef;
SET NOCOUNT ON;
END;
Tried to put them before an update statement, tried to set them individually,
but it did not work.
I ask for help.

Switching a user in SQL Server fails when accessing through user's default schema in stored proc

I'm trying to implement shared API in MS SQL Server 2014 DB. In that architecture, schemas should have similar structures and use shared API owned by dbo whereas at the same time exposes own API. To call one another without qualifying object names, EXECUTE AS USER statement is used for context switching to a certain default schema of the current user.
The problem is here: while immediate access with user context switching works fine (e.g. EXECUTE AS USER followed by SELECT * from test_tbl;), the access through default schema in a stored procedure fails with error Msg 208, Level 16, State 1.
Before posting my question, I tried a lot of experiments and tests and searched MSDN, Web and SQL forums for any clue during several days with no luck.
Scripts for reproducing (<MDF> and <LDF> requires substitutions with appropritate file paths):
-- DB creation
CREATE DATABASE [test_sql]
CONTAINMENT = NONE
ON PRIMARY
( NAME = N'test_sql', FILENAME = N'<MDF>' , SIZE = 5120KB , FILEGROWTH = 1024KB )
LOG ON
( NAME = N'test_sql_log', FILENAME = N'<LDF>' , SIZE = 2048KB , FILEGROWTH = 10%)
COLLATE Cyrillic_General_CI_AS
GO
ALTER DATABASE [test_sql] SET COMPATIBILITY_LEVEL = 120
GO
ALTER DATABASE [test_sql] SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [test_sql] SET ANSI_NULLS OFF
GO
ALTER DATABASE [test_sql] SET ANSI_PADDING OFF
GO
ALTER DATABASE [test_sql] SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [test_sql] SET ARITHABORT OFF
GO
ALTER DATABASE [test_sql] SET AUTO_CLOSE OFF
GO
ALTER DATABASE [test_sql] SET AUTO_SHRINK OFF
GO
ALTER DATABASE [test_sql] SET AUTO_CREATE_STATISTICS ON
GO
ALTER DATABASE [test_sql] SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [test_sql] SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [test_sql] SET CURSOR_DEFAULT GLOBAL
GO
ALTER DATABASE [test_sql] SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [test_sql] SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [test_sql] SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [test_sql] SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [test_sql] SET DISABLE_BROKER
GO
ALTER DATABASE [test_sql] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [test_sql] SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [test_sql] SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [test_sql] SET READ_COMMITTED_SNAPSHOT OFF
GO
ALTER DATABASE [test_sql] SET READ_WRITE
GO
ALTER DATABASE [test_sql] SET RECOVERY FULL
GO
ALTER DATABASE [test_sql] SET MULTI_USER
GO
ALTER DATABASE [test_sql] SET PAGE_VERIFY CHECKSUM
GO
ALTER DATABASE [test_sql] SET TARGET_RECOVERY_TIME = 0 SECONDS
GO
ALTER DATABASE [test_sql] SET DELAYED_DURABILITY = DISABLED
GO
USE [test_sql]
GO
IF NOT EXISTS (SELECT name FROM sys.filegroups WHERE is_default=1 AND name = N'PRIMARY') ALTER DATABASE [test_sql] MODIFY FILEGROUP [PRIMARY] DEFAULT
GO
-- Srv login, DB user and schema creation
CREATE LOGIN [test_usr_login] WITH PASSWORD=N'test_usr_login', DEFAULT_DATABASE=[test_sql], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
GO
CREATE USER [test_usr] FOR LOGIN [test_usr_login] WITH DEFAULT_SCHEMA=[test_schema]
GO
CREATE SCHEMA [test_schema] AUTHORIZATION [test_usr]
GO
-- Table and stored proc creation
IF OBJECT_id("[test_schema].[test_tbl]", "U") IS NOT NULL
DROP TABLE [test_schema].[test_tbl];
GO
CREATE TABLE [test_schema].[test_tbl](
[tc] [nchar](10) NULL
) ON [PRIMARY]
GO
IF OBJECT_id("[dbo].[TA]", "P") IS NOT NULL
DROP PROCEDURE [dbo].[TA];
GO
CREATE PROCEDURE [dbo].[TA] AS BEGIN
SET NOCOUNT ON;
SELECT * FROM
(VALUES
('CURRENT_USER', CURRENT_USER),
('SCHEMA_NAME', SCHEMA_NAME()),
('have_UNqualified_select', cast(HAS_PERMS_BY_NAME("[test_tbl]", "OBJECT", "SELECT") as nchar(10))),
('have_qualified_select', cast(HAS_PERMS_BY_NAME("[test_schema].[test_tbl]", "OBJECT", "SELECT") as nchar(10)))
) AS tmptbl([key], val); -- select permissions fro [test_tbl] of the current user
SELECT tc as qualified_tc FROM [test_schema].[test_tbl]; -- qualified select
SELECT tc as UNqualified_tc from [test_tbl]; -- unqualified select fails with Msg 208
END
GO
GRANT EXECUTE ON [dbo].[TA] TO [test_usr]
GO
Test script:
USE [test_sql]
GO
DECLARE #return_value int
execute as login = N'test_usr_login'; -- even when logged in with test_usr_logn, Msg 208 occurs
EXEC #return_value = [dbo].[TA]
revert
SELECT 'Return Value' = #return_value
GO
Output message:
Msg 208, Level 16, State 1, Procedure TA, Line 14 Invalid object name
'test_tbl'.
(1 row(s) affected)
Output result:
key val
CURRENT_USER test_usr
SCHEMA_NAME test_schema
have_UNqualified_select 1
have_qualified_select 1
I would appreciate anyone who could bring light to the solution to the problem described.
The problem is here: while immediate access with user context
switching works fine (e.g. EXECUTE AS USER followed by SELECT * from
test_tbl;), the access through default schema in a stored procedure
fails with error Msg 208, Level 16, State 1.
The problem here is that you don't know how SQL Server resolves non qualified object name.
When you execute plain sql and use an object without specifying its schema, first user default schema is checked, if object is not found, dbo schema is checked. If the object is not found even in dbo, the error is raised.
It's different when it comes to stored procedure. If schema is not specified, sp's schema is checked first, if object is not found, dbo schema is checked, if it's not found again the error is raised. User default schema is never checked in case of stored procedure

Updating temporal table history

I'm having a problem updating rows in a temporal history table in MS SQL Server 2016.
From the documentation, the steps that should be needed are as follows:
Disable system versioning
Modify the history table
Enable system versioning again
I tried creating a procedure that does this, but got this error:
Msg 13561, Level 16, State 1, Line 23
Cannot update rows in a temporal history table 'db.dbo.FooHistory'.
Here is my SQL:
CREATE TABLE Foo(
id int primary key not null
, title nvarchar(50) not null
, startTime datetime2 GENERATED ALWAYS AS ROW START NOT NULL
, endTime datetime2 GENERATED ALWAYS AS ROW END NOT NULL
, PERIOD FOR SYSTEM_TIME (startTime, endTime) )
ALTER TABLE Foo
SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.FooHistory));
GO
CREATE PROCEDURE [dbo].[UpdateFooHistory] AS
BEGIN
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
ALTER TABLE dbo.Foo SET (SYSTEM_VERSIONING = OFF);
UPDATE dbo.FooHistory
SET title = 'Foo';
ALTER TABLE dbo.Foo SET (SYSTEM_VERSIONING = ON (
HISTORY_TABLE = dbo.FooHistory,
DATA_CONSISTENCY_CHECK = ON
));
COMMIT TRANSACTION
RETURN 0
END
GO
It seems like SQL Server is checking if a table is temporal at "compile time" rather than at runtime. Is this true? Is there a way to work around it?
Change the UPDATE statement to this, and it will let you create the procedure:
EXEC(N'UPDATE dbo.FooHistory SET title = ''Foo''');
With SQL Server 2019 it does not work any more (neither with exec nor with sp_executesql). You need to use a workaround.
In order to prevent any other user to change something while the versioning is off first start a serializable transaction:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
Temporarily disable SYSTEM_VERSIONING on the table:
ALTER TABLE Foo SET (SYSTEM_VERSIONING = OFF);
Modify the history table:
UPDATE dbo.FooHistory SET title = 'Foo';
Re-enable the versioning:
ALTER TABLE Foo SET (SYSTEM_VERSIONING = ON ( HISTORY_TABLE = dbo.FooHistory, DATA_CONSISTENCY_CHECK = ON));
Commit the transaction:
COMMIT TRANSACTION;

how to access a column of a table via foreign key?

I am new in SQL server and having trouble with this trigger code. Can you please tell me what is wrong with this line: set NazivFirme=(select NazivFirme from inserted)... This is where I get an error.
USE [BazaPreduzece]
GO
/****** Object: Trigger [dbo].[promenaNazivaFirme] Script Date: 2017-03-28 5:29:47 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER trigger [dbo].[promenaNazivaFirme]
on [dbo].[Firma]
AFTER UPDATE
as
declare #FirmaID int
select #FirmaID=FirmaID from inserted
if update (NazivFirme)
begin
alter table Vlasnik disable trigger zabranaAzuriranjaNazivaFirme
update [dbo].[Vlasnik]
set NazivFirme=(select NazivFirme from inserted)
where FirmaID=#FirmaID
alter table Vlasnik enable trigger zabranaAzuriranjaNazivaFirme
end
That's theFirma and the Vlasnik tables...

SQL Server error creating a foreign key constraint

I am trying to re-create a foreign key constraint that got deleted recently and SQL Server is not letting me. Here's the DDL that SQL Server Management Studio gave me:
/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE dbo.CleansingOperations SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE dbo.CleansedData ADD CONSTRAINT
FK_CleansedData_CleansingOperations FOREIGN KEY
(
CleansedOperationID
) REFERENCES dbo.CleansingOperations
(
CleansingOperationID
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
ALTER TABLE dbo.CleansedData SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
and here is the error that I get when I run it:
Msg 547, Level 16, State 0, Line 1
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_CleansedData_CleansingOperations". The conflict occurred in database "NetVis203", table "dbo.CleansingOperations", column 'CleansingOperationID'.
Msg 3902, Level 16, State 1, Line 1
The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.
What does it all mean? As far as I can see, it is saying that the constraint is 'conflicting' with itself!
It means that there's a row in CleansedData that doesn't have a corresponding row in CleansingOperations
SELECT CleansingOperationId FROM dbo.CleansedData
EXCEPT
SELECT CleansingOperationId FROM dbo.CleansingOperations
should return no rows for your statement to work.
There's a NOCHECK keyword, which gets around the error, but better to understand what rows would violate the foreign key.
The reason for the error message, is that SQL Server imagines the foreign key is in place and then asserts that all rows satisfy the constraint before committing the statement. The reason for the second error message has to do with error handling (which I can never get right either).

Resources