SQL Server strange duplicate key error - sql-server

In SQL Server 2008 R2, I have a simple table with the following columns definitions:
Id (PK ,int , not null)
MeterId (FK , int ,not null)
InstallDate(DateTime, not null)
Image(NVarCharMax, null)
Number (int , not null)
Comments(NVarChar(300), null)
And Id column is set as Identity .
When I run:
insert into Transmitters (MeterId, Number, InstallDate)
values (952, 777 , '2013-02-21')
I get the duplicate key error.
There is no other transmitter with id 777 ,
There is a meter with id 952.
This started happening in more than 1 table of my DB.
Any suggestions would be most appriceated.
The entire table script is:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Transmitters](
[Id] [int] IDENTITY(1,1) NOT NULL,
[MeterId] [int] NOT NULL,
[InstallDate] [datetime] NOT NULL,
[Image] [nvarchar](max) NULL,
[Number] [int] NOT NULL,
[Comments] [nvarchar](300) NULL,
CONSTRAINT [PK_Transmitters] 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]
GO
ALTER TABLE [dbo].[Transmitters] WITH CHECK ADD CONSTRAINT [FK_Transmitter_Meter] FOREIGN KEY([MeterId])
REFERENCES [dbo].[Meter] ([Id])
GO
ALTER TABLE [dbo].[Transmitters] CHECK CONSTRAINT [FK_Transmitter_Meter]
GO

Ok , thanks guys you've been most helpful.
I've checked my identity current value using:
USE Name_Of_The_DB
GO
DBCC CHECKIDENT (‘Name_Of_The_Table’)
GO
It was indeed the cause of the problem that some rows had higher Id values than
the current identity.
Thand I inserted a row to update the current identity value:
set identity_insert YourTable ON
--Insert my row
set identity_insert YourTable OFF
Thanks :)

Related

How to resolve a null Scope_Indentity on cascaded insert?

I'm performing a cascading insert in a SQL Server stored procedure. Then I pass the SCOPE_IDENTITY from the ID of the first table insert to the second table.
But during executing the stored procedure I get a NULL value for the SCOPE_IDENTITY:
Msg 515, Level 16, State 2, Procedure InsertDDM_UserProfile, Line 43
Cannot insert the value NULL into column 'Filter', table '.....dbo.DDM_Dashboard'; column does not allow nulls. INSERT fails.
Question: why does the stored procedure return a null ID using SCOPE_IDENTITY?
This is the stored procedure I've drafted. FK constraints have already been set up for the tables:
ALTER PROCEDURE [dbo].[InsertDDM_UserProfile]
#p_email VARCHAR(100),
#p_dashboardName VARCHAR(100),
AS
BEGIN
INSERT INTO [dbo].[DDM_User] ([Email])
VALUES (#p_email)
INSERT INTO [dbo].[DDM_Dashboard] ([Dashboard_Name], [DDM_USER_ID])
VALUES (#p_dashboardName, SCOPE_IDENTITY())
END
And below are the two table's structure:
DDM_User-
CREATE TABLE [dbo].[DDM_User]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[Email] [varchar](80) NOT NULL,
CONSTRAINT [PK_DDMUser]
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]
GO
DDM_Dashboard:
CREATE TABLE [dbo].[DDM_Dashboard]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[Dashboard_Name] [varchar](100) NOT NULL,
[DDM_USER_ID] [int] NOT NULL,
CONSTRAINT [PK_DDMDashboard]
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]
GO
ALTER TABLE [dbo].[DDM_Dashboard] WITH NOCHECK
ADD CONSTRAINT [FK_DDMDashboard_DDMUser]
FOREIGN KEY([DDM_USER_ID]) REFERENCES [dbo].[DDM_User] ([ID])
GO
ALTER TABLE [dbo].[DDM_Dashboard] CHECK CONSTRAINT [FK_DDMDashboard_DDMUser]
GO
This is nothing to do with SCOPE_IDENTITY(), during your second insert:
INSERT INTO [dbo].[DDM_Dashboard] ([Dashboard_Name], [DDM_USER_ID])
VALUES (#p_dashboardName, SCOPE_IDENTITY())
You are only inserting into two columns [Dashboard_Name], and [DDM_USER_ID]. You do not specify a value for the column [Filter], which from your error message does not allow null values, therefore your insert fails.
DECLARE #Value1 varchar(50) = 'Test1', #Value2 varchar(50) = 'Test2';
DECLARE #Table1 table (Id int NOT NULL IDENTITY(1,1), Value varchar(50) NOT NULL);
DECLARE #Table2 table (Id int NOT NULL, Value varchar(50) NOT NULL);
INSERT INTO #Table1 (Value1)
OUTPUT inserted.Id, #Value2 INTO #Table2 (Id, Value)
Values (#Value1)
;
SELECT * FROM #Table1;
SELECT * FROM #Table1;
edit:
As GarethD pointed out, this is not actually a valid solution to your problem due to the foreign key constraint. However in other scenarios this is a useful way to handle cascading inserts and updates as it is an atomic operation of both records.

The best mechanism for alter columns of system versioning tables (Temporal Table)?

I have a system-versioning table with history table related as follows:
CREATE TABLE [dbo].[ExpenseCenter_Archive](
[ExpenseCenterId] [tinyint] NOT NULL,
[Name] [nvarchar](200) NOT NULL,
[LineCode] [smallint] NOT NULL,
[SysStartTime] [datetime2](2) NOT NULL,
[SysEndTime] [datetime2](2) NOT NULL
) ON [FG_HISTORY]
GO
-------
CREATE TABLE [dbo].[ExpenseCenter](
[ExpenseCenterId] [tinyint] NOT NULL,
[Name] [nvarchar](200) NOT NULL,
[LineCode] [smallint] NOT NULL,
[SysStartTime] [datetime2](2) GENERATED ALWAYS AS ROW START NOT NULL,
[SysEndTime] [datetime2](2) GENERATED ALWAYS AS ROW END NOT NULL,
CONSTRAINT [PK_ExpenseCenter] PRIMARY KEY CLUSTERED
(
[ExpenseCenterId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [FG_DATA],
CONSTRAINT [UK_ExpenseCenterName] UNIQUE NONCLUSTERED
(
[Name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [FG_INDEX],
PERIOD FOR SYSTEM_TIME ([SysStartTime], [SysEndTime])
) ON [FG_DATA]
WITH
(
SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[ExpenseCenter_Archive] , DATA_CONSISTENCY_CHECK = ON )
)
GO
Now, I want alter data type of 'LineCode' in system-version table and history. After changes once again enabling it as follows:
--- Before edit column
ALTER TABLE [dbo].[ExpenseCenter] SET (SYSTEM_VERSIONING = OFF);
-- ## Edit column in ssms ##
--- After edit column
ALTER TABLE [dbo].[ExpenseCenter]
SET
(
SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[ExpenseCenter_Archive])
);
But I get the following error:
Cannot set SYSTEM_VERSIONING to ON when SYSTEM_TIME period is not defined.
How do I solve this issue.
From your question ,you are saying that ExpenseCenter_archive is the temporal table for ExpenseCenter..but error message says
you don't have system versioned table [dbo].[ExpenseCenter] ,if you want system versioned table ,Add system_time to it
so here are the steps,i would follow to make a table Temporal table of other..
if its for a new table ..
CREATE TABLE Department
(
DeptID int NOT NULL PRIMARY KEY CLUSTERED
, DeptName varchar(50) NOT NULL
, ManagerID INT NULL
, ParentDeptID int NULL
, SysStartTime datetime2 GENERATED ALWAYS AS ROW START NOT NULL
, SysEndTime datetime2 GENERATED ALWAYS AS ROW END NOT NULL
, PERIOD FOR SYSTEM_TIME (SysStartTime,SysEndTime)
)
WITH (SYSTEM_VERSIONING = ON)
;
if i need to alter data type for this newly created table..
MSDN recommends doing it in a transaction..
BEGIN TRAN
ALTER TABLE [dbo].[CompanyLocation] SET (SYSTEM_VERSIONING = OFF);
ALTER TABLE [CompanyLocation] ADD Cntr INT IDENTITY (1,1);
ALTER TABLE [dbo].[CompanyLocation]
SET
(
SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[CompanyLocationHistory])
);
COMMIT ;
If i want to make an existing table Temporal,then i would do like below
ALTER TABLE dbo.Product
ADD StartTime DATETIME2 GENERATED ALWAYS AS ROW START
HIDDEN DEFAULT GETUTCDATE(),
EndTime DATETIME2 GENERATED ALWAYS AS ROW END
HIDDEN DEFAULT
CONVERT(DATETIME2, '9999-12-31 23:59:59.9999999'),
PERIOD FOR SYSTEM_TIME (StartTime, EndTime)
Now finally set Temporal ON
ALTER TABLE dbo.Product
SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE=dbo.ProductHistory))
GO
References:
http://sqlhints.com/tag/modify-existing-table-as-system-versioned-temporal-table/
https://msdn.microsoft.com/en-us/library/mt590957.aspx
for alter system versioning table you don't need set SYSTEM_VERSIONING = OFF, but directly use ALTER TABLE ...

Unable to apply a constraint when data in a column for multiple rows need to be kept unique for a particular foreign key's reference

Let me explain this scenario, with my table structure-
RoomId RoomMemberId
R1 RM1
R1 RM2
R1 RM3
R2 Rm1
R2 RM2
R3 RM1
R3 RM4
R3 RM3
Here in the above table RM1,RM2 and RM3 are the member of R1 room ,
now I have to apply a constraint that there should not be any other room where only these three are members
i.e. there should not be any other room with same room members.
How can i do it at database end, by any unique constraint or any other way to do so ??
Pls help...
Example of Constraint is as given below :
Sample Table
CREATE TABLE TBLROOMTEST
(
ROOMID VARCHAR(100),
ROOMMEMBERID VARCHAR(100)
)
Create function
CREATE FUNCTION dbo.fn_RoomMemberCheck (#room_id varchar(100), #room_member varchar(100))
RETURNS int
AS
BEGIN
DECLARE #retval int
SELECT #retval = CASE WHEN ROOMID = #room_id THEN 1 ELSE 0 END
FROM TBLROOMTEST WHERE ROOMMEMBERID = #room_member
RETURN #retval
END;
Add constraint after table creation(but this can be done at the time of table creation itself):
ALTER TABLE TBLROOMTEST
ADD CONSTRAINT chk_IfMemberExistsInRoom CHECK (dbo.fn_RoomMemberCheck(ROOMID,ROOMMEMBERID)=0);
Note : It will give you error if you already have data in your table, thats why i asked the same to you. Reference is taken from
Here
If the number of room members are limited (say max 5), you could design the table horizontally instead of vertically and artifically make it vertically again in a view.
Room_ID Room_Label
----------- --------------------------------------------------
3 Aconcagua
1 Kilimanjaro
2 Mount Everest
 
Member_ID Member_GivenName Member_LastName
----------- -------------------------------------------------- --------------------------------------------------
1 Alice Smith
2 Bob Taylor
3 Cynthia Miller
4 Dan Cooper
 
RoomMember_ID Room_ID Member1_ID Member2_ID Member3_ID Member4_ID Member5_ID
------------- ----------- ----------- ----------- ----------- ----------- -----------
1 1 1 2 3 NULL NULL
2 2 1 2 NULL NULL NULL
3 3 1 2 3 4 NULL
And the view could look like this:
Room_ID Member_ID
----------- -----------
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
3 4
Then the RoomMember table needs a unique constraint over the members
ALTER TABLE StackOverflow.RoomMember
ADD CONSTRAINT UK_RoomMember01
UNIQUE NONCLUSTERED (
Member1_ID ASC, Member2_ID ASC, Member3_ID ASC, Member4_ID ASC, Member5_ID ASC
)
and a check constraint that ensures the members can only be entered in ascending order from the left to the right with NULL values to the right:
ALTER TABLE [StackOverflow].[RoomMember] WITH CHECK
ADD CONSTRAINT [CK_RoomMembers]
CHECK ((([Member2_ID] IS NULL OR [Member2_ID]>[Member1_ID]) AND ([Member3_ID] IS NULL OR [Member2_ID] IS NOT NULL AND [Member3_ID]>[Member2_ID]) AND ([Member4_ID] IS NULL OR [Member3_ID] IS NOT NULL AND [Member4_ID]>[Member3_ID]) AND ([Member5_ID] IS NULL OR [Member4_ID] IS NOT NULL AND [Member5_ID]>[Member4_ID])))
And that is it. It's now not possible to enter the same combination of members of another room, and the view provides still access in better normalized fashion.
Full source code here:
CREATE TABLE [StackOverflow].[Member](
[Member_ID] [int] IDENTITY(1,1) NOT NULL,
[Member_GivenName] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Member_LastName] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
CONSTRAINT [PK_Member] PRIMARY KEY CLUSTERED
(
[Member_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]
GO
CREATE TABLE [StackOverflow].[Room](
[Room_ID] [int] IDENTITY(1,1) NOT NULL,
[Room_Label] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
CONSTRAINT [PK_Room] PRIMARY KEY CLUSTERED
(
[Room_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [UK_Room] UNIQUE NONCLUSTERED
(
[Room_Label] 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
CREATE TABLE [StackOverflow].[RoomMember](
[RoomMember_ID] [int] IDENTITY(1,1) NOT NULL,
[Room_ID] [int] NOT NULL,
[Member1_ID] [int] NOT NULL,
[Member2_ID] [int] NULL,
[Member3_ID] [int] NULL,
[Member4_ID] [int] NULL,
[Member5_ID] [int] NULL,
CONSTRAINT [PK_RoomMember] PRIMARY KEY CLUSTERED
(
[RoomMember_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [UK_RoomMember01] UNIQUE NONCLUSTERED
(
[Member1_ID] ASC,
[Member2_ID] ASC,
[Member3_ID] ASC,
[Member4_ID] ASC,
[Member5_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]
GO
ALTER TABLE [StackOverflow].[Member] ADD CONSTRAINT [DF_Member_Member_GivenName] DEFAULT (N'') FOR [Member_GivenName]
GO
ALTER TABLE [StackOverflow].[RoomMember] WITH CHECK ADD CONSTRAINT [FK_RoomMember_Member1] FOREIGN KEY([Member1_ID])
REFERENCES [StackOverflow].[Member] ([Member_ID])
GO
ALTER TABLE [StackOverflow].[RoomMember] CHECK CONSTRAINT [FK_RoomMember_Member1]
GO
ALTER TABLE [StackOverflow].[RoomMember] WITH CHECK ADD CONSTRAINT [FK_RoomMember_Member2] FOREIGN KEY([Member2_ID])
REFERENCES [StackOverflow].[Member] ([Member_ID])
GO
ALTER TABLE [StackOverflow].[RoomMember] CHECK CONSTRAINT [FK_RoomMember_Member2]
GO
ALTER TABLE [StackOverflow].[RoomMember] WITH CHECK ADD CONSTRAINT [FK_RoomMember_Member3] FOREIGN KEY([Member3_ID])
REFERENCES [StackOverflow].[Member] ([Member_ID])
GO
ALTER TABLE [StackOverflow].[RoomMember] CHECK CONSTRAINT [FK_RoomMember_Member3]
GO
ALTER TABLE [StackOverflow].[RoomMember] WITH CHECK ADD CONSTRAINT [FK_RoomMember_Member4] FOREIGN KEY([Member4_ID])
REFERENCES [StackOverflow].[Member] ([Member_ID])
GO
ALTER TABLE [StackOverflow].[RoomMember] CHECK CONSTRAINT [FK_RoomMember_Member4]
GO
ALTER TABLE [StackOverflow].[RoomMember] WITH CHECK ADD CONSTRAINT [FK_RoomMember_Member5] FOREIGN KEY([Member5_ID])
REFERENCES [StackOverflow].[Member] ([Member_ID])
GO
ALTER TABLE [StackOverflow].[RoomMember] CHECK CONSTRAINT [FK_RoomMember_Member5]
GO
ALTER TABLE [StackOverflow].[RoomMember] WITH CHECK ADD CONSTRAINT [FK_RoomMember_Room] FOREIGN KEY([Room_ID])
REFERENCES [StackOverflow].[Room] ([Room_ID])
GO
ALTER TABLE [StackOverflow].[RoomMember] CHECK CONSTRAINT [FK_RoomMember_Room]
GO
ALTER TABLE [StackOverflow].[RoomMember] WITH CHECK ADD CONSTRAINT [CK_RoomMembers] CHECK ((([Member2_ID] IS NULL OR [Member2_ID]>[Member1_ID]) AND ([Member3_ID] IS NULL OR [Member2_ID] IS NOT NULL AND [Member3_ID]>[Member2_ID]) AND ([Member4_ID] IS NULL OR [Member3_ID] IS NOT NULL AND [Member4_ID]>[Member3_ID]) AND ([Member5_ID] IS NULL OR [Member4_ID] IS NOT NULL AND [Member5_ID]>[Member4_ID])))
GO
ALTER TABLE [StackOverflow].[RoomMember] CHECK CONSTRAINT [CK_RoomMembers]
GO
CREATE VIEW [StackOverflow].[V_RoomMember]
AS
SELECT Room_ID, Member1_ID AS Member_ID FROM StackOverflow.RoomMember
UNION
SELECT Room_ID, Member2_ID AS Member_ID FROM StackOverflow.RoomMember WHERE Member2_ID IS NOT NULL
UNION
SELECT Room_ID, Member3_ID AS Member_ID FROM StackOverflow.RoomMember WHERE Member3_ID IS NOT NULL
UNION
SELECT Room_ID, Member4_ID AS Member_ID FROM StackOverflow.RoomMember WHERE Member4_ID IS NOT NULL
UNION
SELECT Room_ID, Member5_ID AS Member_ID FROM StackOverflow.RoomMember WHERE Member5_ID IS NOT NULL
GO
SET IDENTITY_INSERT [StackOverflow].[Room] ON
GO
INSERT [StackOverflow].[Room] ([Room_ID], [Room_Label]) VALUES (3, N'Aconcagua')
GO
INSERT [StackOverflow].[Room] ([Room_ID], [Room_Label]) VALUES (1, N'Kilimanjaro')
GO
INSERT [StackOverflow].[Room] ([Room_ID], [Room_Label]) VALUES (2, N'Mount Everest')
GO
SET IDENTITY_INSERT [StackOverflow].[Room] OFF
GO
SET IDENTITY_INSERT [StackOverflow].[Member] ON
GO
INSERT [StackOverflow].[Member] ([Member_ID], [Member_GivenName], [Member_LastName]) VALUES (1, N'Alice', N'Smith')
GO
INSERT [StackOverflow].[Member] ([Member_ID], [Member_GivenName], [Member_LastName]) VALUES (2, N'Bob', N'Taylor')
GO
INSERT [StackOverflow].[Member] ([Member_ID], [Member_GivenName], [Member_LastName]) VALUES (3, N'Cynthia', N'Miller')
GO
INSERT [StackOverflow].[Member] ([Member_ID], [Member_GivenName], [Member_LastName]) VALUES (4, N'Dan', N'Cooper')
GO
SET IDENTITY_INSERT [StackOverflow].[Member] OFF
GO
SET IDENTITY_INSERT [StackOverflow].[RoomMember] ON
GO
INSERT [StackOverflow].[RoomMember] ([RoomMember_ID], [Room_ID], [Member1_ID], [Member2_ID], [Member3_ID], [Member4_ID], [Member5_ID]) VALUES (1, 1, 1, 2, 3, NULL, NULL)
GO
INSERT [StackOverflow].[RoomMember] ([RoomMember_ID], [Room_ID], [Member1_ID], [Member2_ID], [Member3_ID], [Member4_ID], [Member5_ID]) VALUES (2, 2, 1, 2, NULL, NULL, NULL)
GO
INSERT [StackOverflow].[RoomMember] ([RoomMember_ID], [Room_ID], [Member1_ID], [Member2_ID], [Member3_ID], [Member4_ID], [Member5_ID]) VALUES (3, 3, 1, 2, 3, 4, NULL)
GO
SET IDENTITY_INSERT [StackOverflow].[RoomMember] OFF
GO

Exporting null values from Matlab table to SQL Server

I'm trying to export a Matlab table containing "null" values into a SQL Server DB, without any success. Here are my DB settings in Matlab (setdbprefs command):
NullNumberRead: 'NaN'
NullNumberWrite: 'NaN'
NullStringRead: 'null'
NullStringWrite: 'null'
And two example scripts to create the test case.
To create the DB structure:
USE [master]
GO
CREATE DATABASE [TestDB]
GO
USE [TestDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TestTable](
[Field1] [int] IDENTITY(1,1) NOT NULL,
[Field2] [smallint] NULL,
[Field3] [int] NULL,
[Field4] [varchar](10) NULL,
[Field5] [datetime] NULL,
[Field6] [datetime] NULL,
[Field7] [datetime] NULL CONSTRAINT [CreatedOn_DF] DEFAULT (getdate()),
CONSTRAINT [PK_TestTable] PRIMARY KEY CLUSTERED
(
[Field1] 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
SET ANSI_PADDING OFF
GO
To insert a row from Matlab into DB:
% Connect to MS SQL Server Database
conn = database('TestDB','','','Vendor','Microsoft SQL Server',...
'Server','localhost','AuthType','Windows',...
'PortNumber',1433);
% Build record to Export (note that Field1 and Field7 are missing because
% are already generated by destination server)
R = struct('Field2', 1,...
'Field3', 10,...
'Field4', 'abc',...
'Field5', '2016-01-01 00:00:00',...
'Field6', NaN);
% Transform to Table
R = struct2table(R);
% Export to Database
datainsert(conn, '[TestDB].[dbo].[TestTable]', R.Properties.VariableNames, R);
I get the following error, while it should be allowed by Matlab DB prefs.
Error using database/datainsert (line 301)
Unable to insert element in row 1 column 5, NaN. Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]

How to create a table from a schema

I have a table called tbRep in my database
I have 3 schemas on the the SQL Server database
X, Y, Z
now X & Y have tables called X.tbRep & Y.tbRep
However, when I try use the CREATE To script from e.g. X.tbRep and try to create one for the new schema Z, it throws an error saying,
Msg 2714, Level 16, State 6, Line 2
There is already an object named 'tbRep' in the database.
What am I doing wrong here?
I'm sure that there are Z.tbRep doesn't exist
CREATE to script
USE [Info]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [Z].[tbRep](
[ReplicaGroup] [varchar](50) NOT NULL,
[RunFrequencyUnit] [char](1) NOT NULL,
[Enabled] [bit] NOT NULL,
[LastRun] [datetime] NOT NULL,
[RunFrequency] [int] NOT NULL,
[ReplicationWindowType] [char](1) NOT NULL,
[ReplicationWindowSize] [tinyint] NOT NULL,
CONSTRAINT [PK_tbReplicaGroups] PRIMARY KEY CLUSTERED
(
[ReplicaGroup] 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
SET ANSI_PADDING OFF
GO
ALTER TABLE [Z].[tbReplicaGroups] ADD CONSTRAINT [DF_tbReplicaGroups_ReplicationWindowType] DEFAULT ('D') FOR [ReplicationWindowType]
GO
ALTER TABLE [Z].[tbReplicaGroups] ADD CONSTRAINT [DF_tbReplicaGroups_ReplicationWindowSize] DEFAULT ((1)) FOR [ReplicationWindowSize]
GO
--Checks to see if the table doesn't already exist, if not add your creation script
if not exists (select name from sys.tables where name = 'tpRep')
BEGIN
--Table Creation code goes here
END
Can you execute this before CREATE TABLE statement and let us know if you are getting anything?
select *
from sys.all_objects
where sys.all_objects.name = 'tbRep' and
sys.all_objects.type = 'U' and
sys.all_objects.schema_id = (select schema_id from sys.schemas where sys.schemas.name = 'Z')

Resources