SqlDateTime overflow - tsql

On SQL server 2005, I have a table defined as follow:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[DebugTrace](
[Timestamp] [datetime] NOT NULL CONSTRAINT [DF_DebugTrace_Timestamp] DEFAULT (getdate()),
[Log] [nvarchar](max) NOT NULL,
[id] [int] IDENTITY(1,1) NOT NULL,
CONSTRAINT [PK_DebugTrace] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
As you can see, the Timestamp column has a default value set to GetDate().
From the SQL Server Management Studio (running locally on the SQL server), the below code runs fine:
insert into DebugTrace ([Log])
values ('test')
The "same" code ran my workstation fails:
DebugTrace trace = new DebugTrace();
trace.Log = "test from code";
DebugTraces.InsertOnSubmit(trace);
SubmitChanges();
The exception thrown is:
SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and
12/31/9999 11:59:59 PM.
Both requests do not set the Timestamp and rely on the default value to set the column value. Therefore how can the GetDate() function trigger such an exception?
P.S. to request is run from different machines but with the same Windows account

Does DebugTrace's property mapped to TimeStamp, have a default value? Try giving it a default value when inserting from your code
DebugTrace trace = new DebugTrace();
trace.Log = "test from code";
trace.TimeStamp= Datetime.Now;
Your problem is that when inserting, the timestamp is remaining as null. So it could be your default value constraint is not working properly. Have a look at this link, it elaborates your problem precisely.

Related

Check to see if a row or an ID already exist before doing a mass insert on a table

I'm trying to an insert from one database table to another like this:
INSERT INTO factoryDB_Development.dbo.engineList
SELECT *
FROM factoryDB_Staging.dbo.engineList
WHERE engineID NOT IN (SELECT engineID
FROM factoryDB_Development.dbo.engineList)
But I am getting this error:
Cannot insert duplicate key in object 'dbo.engineList'
I am assume it's because that ID already exists in factoryDB_Development.dbo.engineList.
When I checked online at the Microsoft site, I just saw this:
To work around this issue, enable trace flag 8690 to disable the Spool operation
Is there a way to check to see if a row or ID already exists before doing the insert?
Thanks!
If I understood your problem correctly, you want to avoid inserting record in target table if that record with the same ID already exists.
If the ID column in question is a primary key, you can simply set IGNORE_DUP_KEY = ON by recreating the index.
Below is the sample example.
CREATE TABLE [dbo].[Source](
[ID] [int] NULL,
[Name] [varchar](5) NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[Target](
[ID] [int] NOT NULL,
[Name] [varchar](5) NULL,
PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = ON, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
--input sample values in source
INSERT INTO [Source] VALUES (1, 'A') , (1, 'A') , (2, 'B')
--insert data from source to target
INSERT INTO Target
SELECT * FROM Source
DROP TABLE SOURCE
DROP TABLE TARGET

How to insert an identity value into another table

I have two tables:
create table Clients
(
id_client int not null identity(1,1) Primary Key,
name_client varchar(10) not null,
phone_client int not null
)
create table Sales
(
id_sale int not null identity(1,1) Primary Key,
date_sale date not null,
total_sale float not null
id_clients int not null identity(1,1) Foreign Key references Clients
)
So, let's insert into Clients ('Ralph', 00000000), the id_client is going to be 1 (obviously). The question is: How could I insert that 1 into Sales?
FIrst of all - you cannot have two columns defined as identity in any table - you will get an error
Msg 2744, Level 16, State 2, Line 1
Multiple identity columns specified for table 'Sales'. Only one identity column per table is allowed.
So you will not be able to actually create that Sales table.
The id_clients column in the Sales table references an identity column - but in itself, it should not be defined as identity - it gets whatever value your client has.
create table Sales
(
id_sale int not null identity(1,1) Primary Key,
date_sale date not null,
total_sale float not null
id_clients int not null foreign key references clients(id_client)
)
-- insert a new client - this will create an "id_client" for that entry
insert into dbo.Clients(name_client, phone_client)
values('John Doe', '+44 44 444 4444')
-- get that newly created "id_client" from the INSERT operation
declare #clientID INT = SCOPE_IDENTITY()
-- insert the new "id_client" into your sales table along with other values
insert into dbo.Sales(......, id_clients)
values( ......., #clientID)
This works for me like a charm, because as far as I understand, if I migrate user or customer data etc from an old copy of the database, - the identity column and the UId(user id) or CId(customer id) used to give each row it's own unique identity - will become unsynced and therefor I use the second column(TId/UId etc) that contains a copy of the identity column's value to relate my data purely through app logic flow.
I can offset the actual SQL Identity Column(IdColumn) when a migration takes place via inserting and deleting dummy data to the count of the largest number found in that TId/CId etc column with the old data to increment the new database table(s) identity column(s) away from having duplicates on new inserts by using the dummy inserts to push the identity column up to old data values and therefor new customers or users etc will continue to source unique values from the identity column upon new inserts after being filled with the old data which will still contain the old identity values in the second column so that the other data(transactions etc) in other tables will still be in sync with which customer/user is related to said data, be it a transaction or whatever. But not have duplicates as the dummy data will have pushed up the IdColumn value to match the old data.
So if I have say 920 user records and the largest UId is 950 because 30 got deleted. Then I will dummy insert and delete 31 rows into the new table before adding the old 920 records to ensure UId's will have no duplicates.
It is very around the bush, but it works for my limited understanding of SQL XD
What this also allows me to do is delete a migrated user/customer/transaction at a later time using the original UId/CId/TId(copy of identity) and not have to worry that it will not be the correct item being deleted if I did not have the copy and were to be aiming at the actual identity column which would be out of sync if the data is migrated data(inserted into database from old database). Having a copy = happy days. I could use (SET IDENTITY_INSERT [dbo].[UserTable] ON) but I will probably screw that up eventually, so this way is FOR ME - fail safe.
Essentially making the data instance agnostic to an extent.
I use OUTPUT inserted.IdColumn to then save any pictures related using that in the file name and am able to call them specifically for the picture viewer and that data is also migration safe.
To do this, a copy, specifically at insert time, is working great.
declare #userId INT = SCOPE_IDENTITY() to store the new identity value-UPDATE dbo.UserTable to select where to update all in this same transaction
-SET UId = #userId to set it to my second column
-WHERE IdColumn = #userId; to aim at the correct row
USE [DatabaseName]
GO
/****** Object: StoredProcedure [dbo].[spInsertNewUser] Script Date:
2022/02/04 12:09:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spInsertNewUser]
#Name varchar(50),
#PhoneNumber varchar(20),
#IDNumber varchar(50),
#Address varchar(200),
#Note varchar(400),
#UserPassword varchar(MAX),
#HideAccount int,
#UserType varchar(50),
#UserString varchar(MAX)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO dbo.UserTable
([Name],
[PhoneNumber],
[IDNumber],
[Address],
[Note],
[UserPassword],
[HideAccount],
[UserType],
[IsDeleted],
[UserString])
OUTPUT inserted.IdColumn
VALUES
(#Name,
#PhoneNumber,
#IDNumber,
#Address,
#Note,
#UserPassword,
#HideAccount,
#UserType,
#UserString);
declare #userId INT = SCOPE_IDENTITY()
UPDATE dbo.UserTable
SET UId = #userId
WHERE IdColumn = #userId;
END
Here is the create for the table for testing
CREATE TABLE [dbo].[UserTable](
[IdColumn] [int] IDENTITY(1,1) NOT NULL,
[UId] [int] NULL,
[Name] [varchar](50) NULL,
[PhoneNumber] [varchar](20) NULL,
[IDNumber] [varchar](50) NULL,
[Address] [varchar](200) NULL,
[Note] [varchar](400) NULL,
[UserPassword] [varchar](max) NULL,
[HideAccount] [int] NULL,
[UserType] [varchar](50) NULL,
[IsDeleted] [int] NULL,
[UserString] [varchar](max) NULL,
CONSTRAINT [PK_UserTable] PRIMARY KEY CLUSTERED
(
[IdColumn] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

T-SQL Insert into multiple linked tables using a condition and without using a cursor

T-SQL Insert into multiple linked tables using a condition and without using a cursor.
Hello,
I have the following tables
CREATE TABLE [dbo].[TestMergeQuote](
[uid] [uniqueidentifier] NOT NULL,
[otherData] [nvarchar](50) NULL,
CONSTRAINT [PK_TestMergeQuote] PRIMARY KEY CLUSTERED
(
[uid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
ALTER TABLE [dbo].[TestMergeQuote] ADD CONSTRAINT [DF_TestMergeQuote_uid] DEFAULT (newid()) FOR [uid]
--=============
CREATE TABLE [dbo].[TestMergeClient](
[id] [int] IDENTITY(1,1) NOT NULL,
[otherData] [nvarchar](50) NULL,
CONSTRAINT [PK_TestMergeClient] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
--==============
CREATE TABLE [dbo].[TestMergeDocument](
[id] [int] NOT NULL,
[uid_quote] [uniqueidentifier] NOT NULL,
[id_owner] [int] NOT NULL,
[id_keeper] [int] NULL,
[otherData] [nvarchar](50) NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[TestMergeDocument] WITH CHECK ADD CONSTRAINT [FK_TestMergeDocument_TestMergeClient_Keeper] FOREIGN KEY([id_keeper])
REFERENCES [dbo].[TestMergeClient] ([id])
GO
ALTER TABLE [dbo].[TestMergeDocument] CHECK CONSTRAINT [FK_TestMergeDocument_TestMergeClient_Keeper]
GO
ALTER TABLE [dbo].[TestMergeDocument] WITH CHECK ADD CONSTRAINT [FK_TestMergeDocument_TestMergeClient_Owner] FOREIGN KEY([id_owner])
REFERENCES [dbo].[TestMergeClient] ([id])
GO
ALTER TABLE [dbo].[TestMergeDocument] CHECK CONSTRAINT [FK_TestMergeDocument_TestMergeClient_Owner]
GO
ALTER TABLE [dbo].[TestMergeDocument] WITH CHECK ADD CONSTRAINT [FK_TestMergeDocument_TestMergeQuote] FOREIGN KEY([uid_quote])
REFERENCES [dbo].[TestMergeQuote] ([uid])
GO
ALTER TABLE [dbo].[TestMergeDocument] CHECK CONSTRAINT [FK_TestMergeDocument_TestMergeQuote]
GO
AND also table X with other various data.
I want to insert into these three tables the data that already exists in these 3 tables, but giving it different id's, and also replacing some of the data within the X table.
It's a sort of a "copy the data from last year", but add new info.
The condition is that id_keeper is sometimes null, and no insert should be done for it.
I am aware that I have to use OUTPUT and MERGE, but I have no ideea how to achieve something this complex.
The CRUDE code for this using a cursor would be:
DECLARE #OldIdDocument INT, #NewIdDocument INT
DECLARE #OldIdOwner INT, #NewIdOwner INT
DECLARE #OldIdKeeper INT, #NewIdKeeper INT
DECLARE #OldIdQuote UNIQUEINDETIFIER, #NewIdQuote UNIQUEINDETIFIER,
INSERT INTO TestMergeQuote(otherData)
SELECT TOP(1) otherData FROM TestMergeQuote WHERE uid = #OldIdQuote
SET #NewIdQuote = ##IDENTITY
INSERT INTO TestMergeClient(otherData)
SELECT TOP(1) otherData FROM TestMergeClient WHERE uid = #OldIdOwner
SET #NewIdOwner = ##IDENTITY
IF(#OldIdKeeper IS NOT NULL)
BEGIN
INSERT INTO TestMergeClient(otherData)
SELECT TOP(1) otherData FROM TestMergeClient WHERE uid = #OldIdKeeper
SET #NewIdKeeper = ##IDENTITY
END
INSERT INTO TestMergeDocument([uid_quote], [id_owner] , [id_keeper], otherData)
SELECT TOP(1) #NewIdQuote , #NewIdOwner , #NewIdKeeper ,otherData FROM TestMergeDocument WHERE uid = #OldIdDocument
SET #NewIdDocument = ##IDENTITY
You shouldn't have to use a cursor. What I would try is to first pump the data out into separate tables so you can manipulate the data to your heart's content.
Something like this first:
select * into TestMergeQuote_Temp from TestMergeQuote
That will make a new table with the data you want to copy. Of course you can add a where clause to filter the data so you aren't copying a very large table.
Then you can add values, change values, delete values on the _Temp versions.
When you are ready you can insert the data back. Of course you might have to turn auto id off if you have a primary key that is auto-incrementing. Or if you just want new id's and don't want to make id's manually, you should be able to insert the new records just fine and have new id's created for you.
But as a start, try pumping the data into new tables and then worry about inserting after that.

T-SQL to PL/SQL (IDENTITY)

I've got a T-SQL script, that converts field to IDENTITY (in a weird way).
How do I convert it to PL/SQL? (and, probably, figure out, if there is a simpler way to do this - without creating a temporary table).
The T-SQL script:
-- alter table ts_changes add TS_THREADID VARCHAR(100) NULL;
-- Change Field TS_ID TS_NOTIFICATIONEVENTS to IDENTITY
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_TS_NOTIFICATIONEVENTS
(
TS_ID int NOT NULL IDENTITY (1, 1),
TS_TABLEID int NOT NULL,
TS_CASEID int NULL,
TS_WORKFLOWID int NULL,
TS_NOTIFICATIONID int NULL,
TS_PRIORITY int NULL,
TS_STARTDATE int NULL,
TS_TIME int NULL,
TS_WAITSTATUS int NULL,
TS_RECIPIENTID int NULL,
TS_LASTCHANGEDATE int NULL,
TS_ELAPSEDCYCLES int NULL
) ON [PRIMARY]
SET IDENTITY_INSERT dbo.Tmp_TS_NOTIFICATIONEVENTS ON
GO
IF EXISTS(SELECT * FROM dbo.TS_NOTIFICATIONEVENTS)
EXEC('INSERT INTO dbo.Tmp_TS_NOTIFICATIONEVENTS (TS_ID, TS_TABLEID, TS_CASEID, TS_WORKFLOWID, TS_NOTIFICATIONID, TS_PRIORITY, TS_STARTDATE, TS_TIME, TS_WAITSTATUS, TS_RECIPIENTID, TS_LASTCHANGEDATE, TS_ELAPSEDCYCLES)
SELECT TS_ID, TS_TABLEID, TS_CASEID, TS_WORKFLOWID, TS_NOTIFICATIONID, TS_PRIORITY, TS_STARTDATE, TS_TIME, TS_WAITSTATUS, TS_RECIPIENTID, TS_LASTCHANGEDATE, TS_ELAPSEDCYCLES FROM dbo.TS_NOTIFICATIONEVENTS WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT dbo.Tmp_TS_NOTIFICATIONEVENTS OFF
GO
DROP TABLE dbo.TS_NOTIFICATIONEVENTS
GO
EXECUTE sp_rename N'dbo.Tmp_TS_NOTIFICATIONEVENTS', N'TS_NOTIFICATIONEVENTS', 'OBJECT'
GO
ALTER TABLE dbo.TS_NOTIFICATIONEVENTS ADD CONSTRAINT
aaaaaTS_NOTIFICATIONEVENTS_PK PRIMARY KEY NONCLUSTERED
(
TS_ID
) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
COMMIT
From version 12C, Oracle supports the IDENTITY data type e.g.:
CREATE TABLE Tmp_TS_NOTIFICATIONEVENTS
( TS_ID int NOT NULL GENERATED ALWAYS AS IDENTITY.
...
Prior to version 12C, Oracle doesn't have an IDENTITY data type, so there is no equivalent PL/SQL code for this. If you want to ensure that all future inserts automatically get assigned a unique value for TS_ID you can do this:
1) Find out the highest value currently used:
select max(ts_id) from TS_NOTIFICATIONEVENTS;
2) Create a sequence that starts with a value higher than that, e.g.:
create sequence ts_id_seq start with 100000;
3) Create a trigger to populate the column from the sequence on insert:
create or replace trigger ts_id_trig
before insert on TS_NOTIFICATIONEVENTS
for each row
begin
:new.ts_id := ts_id_seq.nextval;
-- or if pre 11G:
-- select ts_id_seq.nextval into :new.ts_id from dual;
end;

Entity Framework Mapping Question

Trying to map the following schema using the Entity Framework.
A Customer can have many associated Stores.
A Store can have many associated Customer
Each Store can have 0 or 1 and only 1 TopCustomer (the criteria to be a TopCustomer is determined in the business logic)
this results with the following mapping in VS.
Here's the DB Script :
USE [TestDb]
GO
/****** Object: Table [dbo].[Customer] Script Date: 06/20/2009 09:53:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Customer](
[CustomerId] [uniqueidentifier] NOT NULL,
[FirstName] [nvarchar](50) NOT NULL,
[LastName] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED
(
[CustomerId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[Store] Script Date: 06/20/2009 09:53:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Store](
[StoreId] [uniqueidentifier] NOT NULL,
[StoreName] [nvarchar](50) NOT NULL,
[TopCustomer] [uniqueidentifier] NULL,
CONSTRAINT [PK_Store] PRIMARY KEY CLUSTERED
(
[StoreId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[CustomerStore] Script Date: 06/20/2009 09:53:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CustomerStore](
[CustomerId] [uniqueidentifier] NOT NULL,
[StoreId] [uniqueidentifier] NOT NULL,
CONSTRAINT [PK_CustomerStore] PRIMARY KEY CLUSTERED
(
[CustomerId] ASC,
[StoreId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: ForeignKey [FK_CustomerStore_Customer] Script Date: 06/20/2009 09:53:52 ******/
ALTER TABLE [dbo].[CustomerStore] WITH CHECK ADD CONSTRAINT [FK_CustomerStore_Customer] FOREIGN KEY([CustomerId])
REFERENCES [dbo].[Customer] ([CustomerId])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[CustomerStore] CHECK CONSTRAINT [FK_CustomerStore_Customer]
GO
/****** Object: ForeignKey [FK_CustomerStore_Store] Script Date: 06/20/2009 09:53:52 ******/
ALTER TABLE [dbo].[CustomerStore] WITH CHECK ADD CONSTRAINT [FK_CustomerStore_Store] FOREIGN KEY([StoreId])
REFERENCES [dbo].[Store] ([StoreId])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[CustomerStore] CHECK CONSTRAINT [FK_CustomerStore_Store]
GO
/****** Object: ForeignKey [FK_Store_TopCustomer] Script Date: 06/20/2009 09:53:52 ******/
ALTER TABLE [dbo].[Store] WITH CHECK ADD CONSTRAINT [FK_Store_TopCustomer] FOREIGN KEY([TopCustomer])
REFERENCES [dbo].[Customer] ([CustomerId])
GO
ALTER TABLE [dbo].[Store] CHECK CONSTRAINT [FK_Store_TopCustomer]
GO
Question :
How can the TopCustomer association be mapped to a single instance of Customer without creating an extra navigation property on the Customer class ?
It sounds like you have the model working and mapping already?
But you just need to remove the extra navigation property?
If you want to remove the navigation property it is pretty simple (although you can't do it the standard EF designer).
You simply open your EDMX file in an XML editor (easy enough inside VS) and delete the unwanted <NavigationProperty .../> from the Customer Entity.
This way the relationship still exists in the Model, but in the class you can only go from
Store.TopCustomer
you can't go the other way.
Hope this helps
Alex
Program Manager Entity Framework Team, Microsoft.