Hey guys I've created a database from this script below. And I am adding a table for State Code and trying to reference GTEDatabaes.State_ID as a foriegn key but I'm getting this error. I can't even drop the constraint because each time I execute the query, it generates a new name. I've posted the script below with inserts removed for easier reading. Thank you
I'm using SQL Server 2012.
create Table State_Code
(State_ID int identity (1,1) primary key,
State_Name varchar(30))
Alter Table GTEDatabases
ADD foreign key (State_Id)
references State_Code (State_ID)
Msg 547, Level 16, State 0, Line 1
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint
"FK__GTEDataba__State__1DE57479". The conflict occurred in database "SBAMaster", table
"dbo.State_Code", column 'State_ID'.
Here's the Script:
USE [SBAMaster]
GO
/****** Object: Table [dbo].[Users] Script Date: 10/12/2012 11:11:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id =
OBJECT_ID(N'[dbo].[Users]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Users](
[User_Id] [int] IDENTITY(1,1) NOT NULL,
[User_First] [nvarchar](30) NULL,
[User_Last] [nvarchar](30) NULL,
[User_Email] [nvarchar](70) NULL,
[User_Pwd] [nvarchar](8) NULL,
[Phone1] [nvarchar](70) NULL,
[Phone2] [nvarchar](70) NULL,
[Active] [bit] NULL,
[SecurityQuestion1] [int] NULL,
[SecurityAnswer1] [nvarchar](500) NULL,
[SecurityQuestion2] [int] NULL,
[SecurityAnswer2] [nvarchar](500) NULL,
[DateEntered] [smalldatetime] NULL,
[Need_Approval] [bit] NULL,
[Can_Approve] [bit] NULL,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED
(
[User_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]
END
GO
SET IDENTITY_INSERT [dbo].[Users] ON
*****Inserts******
GO
SET IDENTITY_INSERT [dbo].[Users] OFF
/****** Object: Table [dbo].[Roles] Script Date: 10/12/2012 11:11:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id =
OBJECT_ID(N'[dbo].[Roles]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Roles](
[Role_Id] [int] IDENTITY(1,1) NOT NULL,
[Role_Name] [nvarchar](20) NULL,
[Role_Description] [nvarchar](50) NULL,
CONSTRAINT [PK_Roles] PRIMARY KEY CLUSTERED
(
[Role_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]
END
GO
SET IDENTITY_INSERT [dbo].[Roles] ON
*****Inserts*******
SET IDENTITY_INSERT [dbo].[Roles] OFF
/****** Object: Table [dbo].[GTEDatabases] Script Date: 10/12/2012 11:11:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID
(N'[dbo].[GTEDatabases]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[GTEDatabases](
[GteDatabases_Id] [int] IDENTITY(1,1) NOT NULL,
[CustName] [nvarchar](50) NULL,
[Databasename] [nvarchar](50) NULL,
[Active] [bit] NULL,
[DateEntered] [smalldatetime] NULL,
[CustNumber] [nvarchar](30) NULL,
[Address1] [nvarchar](200) NULL,
[Address2] [nvarchar](200) NULL,
[Zip] [nvarchar](15) NULL,
[City_Id] [int] NULL,
[State_Id] [int] NULL,
[Country_Id] [int] NULL,
[Cust_Since] [int] NULL,
[Primary_ContactName] [nvarchar](30) NULL,
[Primary_Email] [varchar](60) NULL,
[Primary_Phone] [nvarchar](20) NULL,
[Secondary_ContactName] [nvarchar](30) NULL,
[Secondary_Email] [varchar](60) NULL,
[Secondary_Phone] [nvarchar](20) NULL,
[Notes] [nvarchar](500) NULL,
[SBASalRep_Email] [nvarchar](60) NULL,
[CSRCon_Email] [nvarchar](60) NULL,
[AllowPO] [bit] NULL,
[CMSCustomer] [bit] NULL,
CONSTRAINT [PK_GTEDatabases] PRIMARY KEY CLUSTERED
(
[GteDatabases_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]
END
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[GTEDatabases] ON
***Inserts*****
SET IDENTITY_INSERT [dbo].[GTEDatabases] OFF
You didn't see FK in scripts because there's error occurs while your attempting to create FK constrains.
An FK constraint requires that each values in the reference column in source table must exists in the referenced column of target column.
In this case, it could be that some data exists in GTEDatabases table while State_Code is empty. So, while attempting to create FK, db engines will check if all State_id values in GTEDatabases could be found in State_id column in State_Code table, and it will refuse to complete the operation when check fails.
Related
I want to display Data after Secure Login. Using Label and textboxes. And also want to use session variable to expire login.
My problem is that. how to display this data in user Home page.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblEmployeeDetail](
[EmployeeID] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [nvarchar](25) NOT NULL,
[LastName] [nvarchar](25) NOT NULL,
[UserName] [nvarchar](50) NOT NULL,
[Gender] [nvarchar](20) NOT NULL,
[Password] [nvarchar](50) NOT NULL,
[Email] [nvarchar](50) NOT NULL,
[Telephone] [bigint] NOT NULL,
[HouseNo] [nvarchar](25) NOT NULL,
[Street] [nvarchar](25) NOT NULL,
[Locality] [nvarchar](25) NOT NULL,
[City] [nvarchar](50) NOT NULL,
[State] [nvarchar](50) NOT NULL,
[Pincode] [int] NOT NULL,
[Country] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_tblEmployeeDetail] PRIMARY KEY CLUSTERED
(
[EmployeeID] 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
Facebook basically shows the data of your friends, the pages u liked, or the links u posted, commented or liked. That means each data what is are getting in your page is somehow related with you. It is basically the relationship between all these tables where the data is managed. Use join on the bases of userId and user friends userIds, you will get all the data you require.
I am using SQL Server 2008 to maintain a database where I have an userAcccounts table where the user details are stored while registering on the website. The userID column is an integer with identity on.
What I have noticed is that somehow, the column is skipping some ids (random number of ids, sometimes it skips 5,11,10 etc), i.e., the ID's are not consecutive. I have a read a similar question here, with a similar issue which suggested
"An identity sequence is incremented any time an insert is attempted
-- this includes a failed or rolled back INSERT"
I have checked my logs for errors, but there were no error during the period when the ids were skipped. Also my insert is not within any transaction for a rollback to happen, because there is no requirement of deleting an account. Also no other tables are involved during the registration
Although this is not a major issue as the ids will be unique nevertheless, what I would like to find out is why this behavior?
Perhaps I am overlooking something.
Are there any other scenarios where this kind of behavior can occur? i.e. the identity column skipping a few ids? Could this be an issue with concurrent access?
here is the table's create script.
CREATE TABLE [dbo].[UserAccounts](
[AccountID] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [varchar](30) NULL,
[LastName] [varchar](30) NULL,
[Gender] [varchar](10) NULL,
[Email] [varchar](150) NULL,
[EmailVerified] [bit] NULL,
[UserName] [varchar](30) NULL,
[Password] [varchar](50) NULL,
[ProfilePicture] [varchar](150) NULL,
[BackgroundPicture] [varchar](150) NULL,
[DateOfBirth] [smalldatetime] NULL,
[CreateDate] [smalldatetime] NULL,
[LastUpdatedOn] [smalldatetime] NULL,
[Points] [int] NULL,
[CurrentBadge] [varchar](30) NULL,
[FBID] [varchar](50) NULL,
[TwitterID] [varchar](50) NULL,
[Abused] [int] NULL,
[isActive] [bit] NULL,
[AccountTypeID] [int] NULL,
[DateStamp] [timestamp] NOT NULL,
[Location] [varchar](50) NULL,
[About] [varchar](250) NULL,
[UsingBackgroundPicture] [bit] NULL,
CONSTRAINT [PK__UserAcco__349DA5867F60ED59] PRIMARY KEY CLUSTERED
(
[AccountID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Any help in this regard is appreciated? Also if you require any other detail, please let me know.
Thanks
It's impossible to guarantee exact sequentiality of Sequences or IDs, without globally locking the entire database on every transaction -- to prevent any concurrent transactions, which could possibly also ask for an ID.
This would obviously reduce it to effectively a single-user database, and totally destroy performance.
For such reasons, there is explicitly no guarantee of continuous sequentiality.
We have a application where users are entering their time efforts .We have two tables, Production table for entering all production tasks and NonProduction for entering all non production related tasks in the application.We also have a UserInfo table where all the user information is stored like his eCode, Name, Designation,RoleID,ImmediateSupervisor ECode to whom the user is reporting etc.
We are trying to make a sql query in such manner so that any users whose roleid is greater then 1 can drill down and extract the Production and NonProduction information of the users reporting under him but the condition is that the extracted report is of RoleID 1 only.
For example, A Manager RoleID is 4 ,so firstly he drill down and find all the users reporting to him (This info is in ImmediateSupervisor column on UserInfo table)i.e RoleID 3 or RoleID 4, then again we drill down to these Users and extract information who are reporting to them and continue until we drill down up to ROleID 1 and once we drill down to that level, we extract respective users Production and NonProduction details and display in the Report.
Below is the table structure query in Create Table format;
Production Table
CREATE TABLE [dbo].[Production]
(
[ProductionTimeEntryID] [int] IDENTITY(100, 1) NOT NULL,
[CalendarDate] [datetime] NOT NULL,
[UserID] [int] NOT NULL,
[NatureOfWorkID] [int] NOT NULL,
[RegionProjectID] [int] NOT NULL,
[CountyID] [int] NOT NULL,
[WorkTypeID] [int] NOT NULL,
[TaskID] [int] NOT NULL,
[VolumeProcessed] [int] NOT NULL,
[NosOfError] [int] NULL,
[NosOfVolumeAudited] [int] NULL,
[TimeSpent] [varchar](25) NULL,
[Comment] [varchar](250) NULL,
[IsTaskCompleted] [int] NOT NULL,
[isCurrentDayTask] [bit] NOT NULL,
[SupervisorECode] [nvarchar](50) NULL,
CONSTRAINT [PK_Production] PRIMARY KEY CLUSTERED([ProductionTimeEntryID] 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 [dbo].[Production] WITH NOCHECK ADD CONSTRAINT
[FK_Production_County] FOREIGN KEY([CountyID])
REFERENCES [dbo].[County] ([CountyID])
GO
ALTER TABLE [dbo].[Production] CHECK CONSTRAINT [FK_Production_County]
GO
ALTER TABLE [dbo].[Production] WITH NOCHECK ADD CONSTRAINT
[FK_Production_NatureOfWork] FOREIGN KEY([NatureOfWorkID])
REFERENCES [dbo].[NatureOfWork] ([NatureOfWorkID])
ON
UPDATE CASCADE
ON
DELETE CASCADE
GO
ALTER TABLE [dbo].[Production] CHECK CONSTRAINT [FK_Production_NatureOfWork]
GO
ALTER TABLE [dbo].[Production] WITH NOCHECK ADD CONSTRAINT
[FK_Production_RegionAndProjectInfo] FOREIGN KEY([RegionProjectID])
REFERENCES [dbo].[RegionAndProjectInfo] ([RegionProjectID])
GO
ALTER TABLE [dbo].[Production] CHECK CONSTRAINT
[FK_Production_RegionAndProjectInfo]
GO
ALTER TABLE [dbo].[Production] WITH CHECK ADD CONSTRAINT
[FK_Production_Task] FOREIGN KEY([TaskID])
REFERENCES [dbo].[Task] ([TaskID])
GO
ALTER TABLE [dbo].[Production] CHECK CONSTRAINT [FK_Production_Task]
GO
ALTER TABLE [dbo].[Production] WITH CHECK ADD CONSTRAINT
[FK_Production_USERINFO] FOREIGN KEY([UserID])
REFERENCES [dbo].[USERINFO] ([UserID])
ON
UPDATE CASCADE
ON
DELETE CASCADE
GO
ALTER TABLE [dbo].[Production] CHECK CONSTRAINT [FK_Production_USERINFO]
GO
ALTER TABLE [dbo].[Production] WITH CHECK ADD CONSTRAINT
[FK_Production_WorkType] FOREIGN KEY([WorkTypeID])
REFERENCES [dbo].[WorkType] ([WorkTypeID])
ON
UPDATE CASCADE
ON
DELETE CASCADE
GO
ALTER TABLE [dbo].[Production] CHECK CONSTRAINT [FK_Production_WorkType]
GO
ALTER TABLE [dbo].[Production] ADD DEFAULT((0)) FOR [IsTaskCompleted]
GO
ALTER TABLE [dbo].[Production] ADD DEFAULT((0)) FOR [isCurrentDayTask]
GO
UserInfo Table:
CREATE TABLE [dbo].[USERINFO](
[UserID] [int] IDENTITY(1,1) NOT NULL,
[UserECode] [nvarchar](50) NOT NULL,
[UserName] [nvarchar](250) NOT NULL,
[CCCode] [nvarchar](50) NULL,
[CCName] [nvarchar](50) NULL,
[Password] [varchar](50) NULL,
[IsFlagEnabled] [bit] NULL,
[IsFirstTimeUserLoggedIn] [bit] NULL,
[EmailAddress] [nvarchar](250) NULL,
[Designation] [varchar](50) NULL,
[ShiftStartTime] [varchar](8) NULL,
[ShiftEndTime] [varchar](8) NULL,
[WeekendShiftStartTime] [varchar](8) NULL,
[WeekendShiftEndTime] [varchar](8) NULL,
[RoleID] [int] NULL,
[ShiftEndFlagStatus] [int] NOT NULL,
[ShiftStartTimeWithTimeStamp] [datetime] NULL,
[ShiftEndTimeWithTimeStamp] [datetime] NULL,
[LoggedInDateTime] [datetime] NULL,
[FirstLoggedInOnthedayflag] [int] NOT NULL,
[ImmediateSupervisor] [nvarchar](50) NULL,
CONSTRAINT [PK_USER] PRIMARY KEY CLUSTERED
(
[UserID] 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 [dbo].[USERINFO] ADD DEFAULT ((1)) FOR [RoleID]
GO
ALTER TABLE [dbo].[USERINFO] ADD DEFAULT ((1)) FOR [ShiftEndFlagStatus]
GO
ALTER TABLE [dbo].[USERINFO] ADD DEFAULT ((1)) FOR [FirstLoggedInOnthedayflag]
GO
How to make such query or type of query to incorporate same in my application?
You have a table with a tree structure, the standard way to extract this is to use a recursive cte, something like this:
;with UserTree as
(
select UserECode, UserID
from USERINFO
where UserID = <the managers user-id>
union all
select UserECode, UserID
from UserTree parent
inner join USERINFO child
on child.ImmediateSupervisor = parent.UserECode
)
select * --change this to the specific columns that you need
from UserTree ut
inner join Production p
on p.UserID = ut.UserID
where RoleId = 1
Please note that I haven't managed to test this code, but I'm sure you can fix any minor issues yourself.
More information about recursive cte:s.
I also couldn't help but notice a couple of potential issues with your tree datastructure: ImmediateSupervisor appears to reference UserECode, and I can see two problems in the table structure that you have posted:
No foreign key from ImmediateSupervisor to UserECode. This could result in users that have non-existing supervisors.
UserECode is not unique. This could result in multiple users with the same code, which means multiple supervisors per user, and that will really screw up the recursive cte query.
I don't have the whole picture here, but with what I have I would change the ImmediateSupervisor-column to refer to the PK UserId instead.
with
ProductionCTE(CalendarDate,RoleID,UserID,UserECode,UserName,ImmediateSupervisor,NatureOfWorkName,RegionProjectName,CountyName,WorkTypeName,TaskName,VolumneProcessed,TimeSpent,Comment)
as
(
select P.CalendarDate,U.RoleID,U.UserID,U.UserECode,U.UserName,U.ImmediateSupervisor,N.NatureofWorkName,
R.RegionProjectName,C.Countyname,W.WorktypeName,T.TaskName,P.VolumeProcessed,P.Timespent,P.Comment
from production P inner join NatureOfWork N
on N.NatureofWorkID=P.natureofworkid
inner join dbo.RegionAndProjectInfo R
on R.RegionProjectID=P.RegionProjectID
inner join county C
on C.countyid=P.countyid
inner join worktype W
on W.Worktypeid=P.worktypeID
inner join task T
on T.taskid=P.TaskID
inner join UserInfo U
on U.Userid=P.userid
where P.userid=952
union all
select P.CalendarDate,U.RoleID,U.UserID,U.UserECode,U.UserName,U.ImmediateSupervisor,N.NatureofWorkName,
R.RegionProjectName,C.Countyname,W.WorktypeName,T.TaskName,P.VolumeProcessed,P.Timespent,P.Comment
from production P inner join NatureOfWork N
on N.NatureofWorkID=P.natureofworkid
inner join dbo.RegionAndProjectInfo R
on R.RegionProjectID=P.RegionProjectID
inner join county C
on C.countyid=P.countyid
inner join worktype W
on W.Worktypeid=P.worktypeID
inner join task T
on T.taskid=P.TaskID
inner join UserInfo U
on U.Userid=P.userid
inner join ProductionCTE
on U.ImmediateSupervisor=ProductionCTE.UserECode
)
select distinct CalendarDate,RoleID,UserID,UserECode,UserName,ImmediateSupervisor,NatureOfWorkName,RegionProjectName,CountyName,WorkTypeName,TaskName,VolumneProcessed,TimeSpent,Comment from ProductionCTE order by UserECode
Implementing Recursive CTE fixed the issue and now ia m able to extract the records as per hierarchy.
I know that SimpleMembership will auto create the tables needed for authentication but I would much rather run the sql scripts at some time other than when the application is ran. Is there a download page for the SimpleMembership scripts?
I found a script on github
CREATE TABLE [dbo].[UserProfile] (
[UserId] INT IDENTITY (1, 1) NOT NULL,
[UserName] NVARCHAR (MAX) NULL,
PRIMARY KEY CLUSTERED ([UserId] ASC)
);
CREATE TABLE [dbo].[webpages_Membership] (
[UserId] INT NOT NULL,
[CreateDate] DATETIME NULL,
[ConfirmationToken] NVARCHAR (128) NULL,
[IsConfirmed] BIT DEFAULT ((0)) NULL,
[LastPasswordFailureDate] DATETIME NULL,
[PasswordFailuresSinceLastSuccess] INT DEFAULT ((0)) NOT NULL,
[Password] NVARCHAR (128) NOT NULL,
[PasswordChangedDate] DATETIME NULL,
[PasswordSalt] NVARCHAR (128) NOT NULL,
[PasswordVerificationToken] NVARCHAR (128) NULL,
[PasswordVerificationTokenExpirationDate] DATETIME NULL,
PRIMARY KEY CLUSTERED ([UserId] ASC)
);
CREATE TABLE [dbo].[webpages_OAuthMembership] (
[Provider] NVARCHAR (30) NOT NULL,
[ProviderUserId] NVARCHAR (100) NOT NULL,
[UserId] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Provider] ASC, [ProviderUserId] ASC)
);
CREATE TABLE [dbo].[webpages_Roles] (
[RoleId] INT IDENTITY (1, 1) NOT NULL,
[RoleName] NVARCHAR (256) NOT NULL,
PRIMARY KEY CLUSTERED ([RoleId] ASC),
UNIQUE NONCLUSTERED ([RoleName] ASC)
);
CREATE TABLE [dbo].[webpages_UsersInRoles] (
[UserId] INT NOT NULL,
[RoleId] INT NOT NULL,
PRIMARY KEY CLUSTERED ([UserId] ASC, [RoleId] ASC),
CONSTRAINT [fk_UserId] FOREIGN KEY ([UserId]) REFERENCES [dbo].[UserProfile] ([UserId]),
CONSTRAINT [fk_RoleId] FOREIGN KEY ([RoleId]) REFERENCES [dbo].[webpages_Roles] ([RoleId])
);
After creating an index on a rather small table (approx. 700 rows, 10 colums) I started to get
System.Data.SqlClient.SqlException: Timeout expired
The index was clusterd on the primary key.
There are no triggers.
All of these errors occured when doing an update via a stored procedure.
After I removed the index I had no more time-out issues.
Setting CommandTimeout did not help.
Does anybody has an idea why this was happening?
stored procedure (nothing special here)
Update objects set date_last_datacollect=#date_last_datacollect,
date_last_error='',message_last_error='' where objectid = #objectid
Table structure
CREATE TABLE [dbo].[objects](
[id] [int] IDENTITY(1,1) NOT NULL,
[objectid] [nvarchar](50) NULL,
[name] [nvarchar](max) NULL,
[adminid] [nvarchar](50) NULL,
[token] [nvarchar](max) NULL,
[type] [nvarchar](max) NULL,
[date_added] [date] NULL,
[date_last_update] [datetime] NULL,
[date_last_datacollect] [datetime] NULL,
[date_last_error] [datetime] NULL,
[message_last_error] [nvarchar](max) NULL,
[active] [bit] NULL,
[logourl] [nchar](255) NULL
) ON [PRIMARY]
edit:
After viewing my table structure I realize it might be due to the missing primary key?
Have you tried updating statistics on the table?