How to reset auto-increment in SQL Server? - sql

I've been having this problem with my database where it kept on incrementing the id column even though it has been removed. To better understand what I meant, here is a screenshot of my gridview:
As you can see from the id column, everything is fine from 11 - 16. but it suddenly skipped from 25 - 27. What i want to happen is, when i remove an item, i want it to start from the last id which is 16. So the next id should be 17. I hope this makes sense for you guys.
Here is also part of the SQL script:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[guitarItems]
(
[id] [int] IDENTITY(1,1) NOT NULL,
[type] [varchar](50) NOT NULL,
[brand] [varchar](50) NOT NULL,
[model] [varchar](50) NOT NULL,
[price] [float] NOT NULL,
[itemimage1] [varchar](255) NULL,
[itemimage2] [varchar](255) NULL,
[description] [text] NOT NULL,
[necktype] [varchar](100) NOT NULL,
[body] [varchar](100) NOT NULL,
[fretboard] [varchar](100) NOT NULL,
[fret] [varchar](50) NOT NULL,
[bridge] [varchar](100) NOT NULL,
[neckpickup] [varchar](100) NOT NULL,
[bridgepickup] [varchar](100) NOT NULL,
[hardwarecolor] [varchar](50) NOT NULL,
PRIMARY KEY CLUSTERED ([id] ASC)
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

You can use:
DBCC CHECKIDENT ("YourTableNameHere", RESEED, 1);
Before using it, visit link: https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkident-transact-sql

Primary autoincrement keys in the database are used to uniquely identify a given row and shouldn't be given any business meaning. So leave the primary key as it is and add another column like guitarItemsId. Then when you delete a record from the database you may want to send an additional UPDATE statement in order to decrease the guitarItemsId column of all rows that have the guitarItemsId greater than the one you are currently deleting.
Also, remember that you should never modify the value of a primary key in a relational database because there could be other tables that reference it as a foreign key and modifying it might violate the referential constraints.

Related

SQL Server : How to combine multiple database into one database?

From my original database, I made changes to some tables with columns in the table, I want to merge them into a single database. New database just add some table and old table add some columns.
How to merge multiple database into one database?
SQL example:
CREATE TABLE [dbo].[Item]
(
[ItemID] [nchar](10) NOT NULL,
[Money] [bigint] NOT NULL,
[ItemName] [bigint] NOT NULL,
[MoneyType] [bigint] NOT NULL,
CONSTRAINT [PK_Item]
PRIMARY KEY CLUSTERED ([ItemID] ASC) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Account]
(
[Index] [int] IDENTITY(1,1) NOT NULL,
[AccountID] [nchar](10) NOT NULL,
[AccountName] [int] NOT NULL,
[ItemList] [int] NOT NULL,
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Money]
(
[AccountID] [nchar](10) NOT NULL,
[Money] [bigint] NOT NULL,
[MoneyType] [bigint] NOT NULL,
CONSTRAINT [PK_Money]
PRIMARY KEY CLUSTERED ([AccountID] ASC) ON [PRIMARY]
) ON [PRIMARY]
GO
-> Nick.McDermaid: use the schema compare tool in Visual Studio (various free editions) which will create a change script!
This will combine them onto DBCombined.Account if the Account table does NOT exist yet: the SELECT INTO code creates the target table. You would then need to add any indexes from the original tables. Also, "SELECT *" should really be broken out, listing each field, because if you have an ID field it will contain duplicates. Better to leave ID off during the insert and then go back and add an identity column.
USE DBCombined
GO
SELECT *
INTO Account
FROM (
SELECT *
FROM DB1.dbo.Account
UNION ALL
SELECT *
FROM DB2.dbo.Account
) Acct

SQL Server Computed Column as Primary Key

I've created a table with a computed column as the primary key.
Table is created fine.And here is the script..
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ARITHABORT ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [planning.A062].[RMAllocation](
[Id] [int] IDENTITY(100,1) NOT NULL,
[RMAllocatonId] AS ('RMA_'+CONVERT([nvarchar](100),[Id])) PERSISTED NOT NULL,
[RequsitionNo] [nvarchar](100) NULL,
[RMDemandId] [nvarchar](104) NULL,
[HierarchyId] [nvarchar](102) NULL,
[Season] [nvarchar](50) NULL,
[VendorSupplierNo] [nvarchar](100) NULL,
[Year] [int] NULL,
[Month] [int] NULL,
[Week] [int] NULL,
[Day] [int] NULL,
[PlannedQty] [int] NULL,
[ConfirmedQty] [int] NULL,
[Status] [int] NULL,
[CreatedBy] [int] NULL,
[SyncId] [nvarchar](100) NULL,
[CreatedOn] [datetime2](7) NULL,
[UpdatedBy] [int] NULL,
[UpdatedOn] [datetime2](7) NULL,
[IsActive] [bit] NULL,
[RecordDateTime] [datetime2](7) NULL,
CONSTRAINT [PK_RMAllocation] PRIMARY KEY CLUSTERED
(
[RMAllocatonId] 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
The problem is when I change this table (Add/edit a column ) using Designer View,it gives me the following error.
error
Unable to create index 'PK_RMAllocation'.
Cannot define PRIMARY KEY constraint on nullable column in table 'RMAllocation'.
Could not create constraint. See previous errors.
When I use script to do modifications,it works. And Even I have declared the computed column as NOT NULL. How this happen??
Something is wrong with the designer. SQL Server is quite clear in the documentation that computed columns can be used for primary keys (for instance, here).
My guess is that the designer is dropping all constraints on the table and adding them back in. It ends up adding them in the wrong order, so the primary key is assigned before the not null on the computed column. I have no idea if there is any work-around other than the obvious one of not using the designer.
According to the documentation (emphasis mine)
A computed column cannot be used as a DEFAULT or FOREIGN KEY
constraint definition or with a NOT NULL constraint definition.
So it may be somewhat surprising that it works at all even in TSQL.
When the designer implements the change by recreating the table, it loses the NOT NULL on the column definition.
[Id] [int] IDENTITY(100,1) NOT NULL,
[RMAllocatonId] AS ('RMA_'+CONVERT([nvarchar](100),[Id])) PERSISTED,
[RequsitionNo] [nvarchar](100) NULL,
Semantically this concatenation of a NOT NULL constant and a NOT NULL column can never be NULL anyway.
Another way you can persuade SQL Server that the column will be NOT NULL-able even in the absence of a NOT NULL is by wrapping the definition in an ISNULL.
The following works fine with the designer
[RMAllocatonId] AS (ISNULL('RMA_'+CONVERT([nvarchar](100),[Id]),'')) PERSISTED
At insert time the system doesn't know the new [id] value. You need a trigger that update the value later.
When two Id values are same, corresponding RMAllocatonId values will be same. When two Id values are different, corresponding RMAllocatonId values will be different. So making the Id unique is equivalent to making RMAllocatonId unique.
If you ask me, just put the PRIMARY KEY on Id where it belongs and be done with it...

Get value from other foreign key table based on current table value

I am working on a project where I need to extract the data from excel sheet to SQL Server
, well that bit have done successfully. Now my problem is that for a particular column
called product size, I want to update current table based on product size in other table, I am really very confused , please help me out
Please find the table structure
CREATE TABLE [dbo].[T_Product](
[ProductID] [int] IDENTITY(1,1) NOT NULL,
[PartNo] [nvarchar](255) NULL,
[CategoryID] [int] NULL,
[MaterialID] [float] NULL,
[WireformID] [float] NULL,
[ProductName] [nvarchar](50) NULL,
[ProductSize] [nvarchar](50) NULL,
[ProductLength] [varchar](20) NULL,
[ProductActive] [bit] NULL,
[ProductImage] [varchar](60) NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[T_ProductSize](
[Code] [int] IDENTITY(1,1) NOT NULL,
[ProductSize] [nvarchar](50) NULL,
[Length] [nchar](20) NULL
) ON [PRIMARY]
GO
OK, so ignore the previous answer, I got the wrong end of the stick!!
You want something like this I think:
UPDATE T_Product
SET [ProductLength] = ps.[Length]
FROM T_Product p
INNER JOIN T_ProductSize ps
ON p.[ProductSize] = ps.[ProductSize]
That will take the Length value from T_ProductSize and place it in T_Product.ProductLength based on the value of T_Product.ProductSize
You mention a foreign key but you haven't included a definition for it. Is it between the two tables in your example? If so, which columns make the key? Is product size the key? If so, then your question doesn't make a lot of sense as the value will be the same in both tables.
Is it possible that you mean the product size is to be stored in a separate table and not in the T_Product table? In that case then instead of ProductSize in T_Product you will want the code from the T_ProductSize table (can I also suggest that instead of 'code' you call it 'ProductSizeCode' or better yet 'ProductSizeId' or similar? having columns simply called code can be very confusing as you have no simple way of know what table that value is in). Also, you should always create a primary key on each table: You cannot have a foreign key without one. They don't have to be clustered, that will depend upon hwo your search the table, but I am using a clustered PK for this example. That would give you something like this:
CREATE TABLE [dbo].[T_Product](
[ProductID] [int] IDENTITY(1,1) NOT NULL,
[PartNo] [nvarchar](255) NULL,
[CategoryID] [int] NULL,
[MaterialID] [float] NULL,
[WireformID] [float] NULL,
[ProductName] [nvarchar](50) NULL,
[ProductSizeId] [int] NOT NULL,
[ProductLength] [varchar](20) NULL,
[ProductActive] [bit] NULL,
[ProductImage] [varchar](60) NULL
CONSTRAINT [PK_T_Product] PRIMARY KEY CLUSTERED
(
[ProductID] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[T_ProductSize](
[ProductSizeId] [int] IDENTITY(1,1) NOT NULL,
[ProductSize] [nvarchar](50) NULL,
[Length] [nchar](20) NULL
CONSTRAINT [PK_T_ProductSize] PRIMARY KEY CLUSTERED
(
[ProductSizeId] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO
--Now add your foreign key to T_Product.
ALTER TABLE [T_Product] WITH NOCHECK ADD CONSTRAINT [FK_Product_ProductSize] FOREIGN KEY([ProductSizeId])
REFERENCES [T_ProductSize] ([ProductSizeId])
GO
ALTER TABLE [T_Product] CHECK CONSTRAINT [FK_Product_ProductSize]
GO
Now, to retrieve your product along with the product size use something like this:
SELECT p.[ProductID], p.[PartNo], p.[CategoryID], p.[MaterialID], p.[WireformID], p.[ProductName],
ps.[ProductSize], ps.[Length], p.[ProductLength], p.[ProductActive], p.[ProductImage]
FROM [T_Product] p
INNER JOIN [T_ProductSize] ps
ON ps.[ProductSizeId] = p.[ProductSizeId]
If I have understood you correctly, then this is what I think you're after. If not, then have another go at explaining what it is you need and I'll try again.
Try this...
UPDATE t2
SET t2.ProductLength = t1.Length
FROM dbo.T_ProductSize t1
INNER JOIN dbo.T_Product t2 ON t1.ProductSize = t2.ProductSize

How do I give a name to a primary key constraint?

I have (another) question about indexing.
I use the following code:
CREATE TABLE [dbo].[PnrDetails1](
[OId] [int] IDENTITY(1,1) NOT NULL ,
[file_name] [varchar](256) NOT NULL,
[gds_id] [int] NOT NULL,
[pnr_locator] [varchar](15) NOT NULL,
[first_cust_name] [varchar](50) NOT NULL,
[ticket_number] [varchar](20) NOT NULL,
[full_price] [decimal](18, 0) NOT NULL,
[currency_desc] [varchar](4) NOT NULL,
[user_name] [varchar](50) NOT NULL,
[save_time] [datetime] NOT NULL,
[update_time] [datetime] NOT NULL,
[clerk_id] [int] NOT NULL,
[isUpdated] [bit] NOT NULL,
[isDeleted] [bit] NOT NULL,
[pnr_file_id] [int] NOT NULL
) ON [PRIMARY]
ALTER TABLE [dbo].[PnrDetails1] ADD PRIMARY KEY CLUSTERED
(
[OId] ASC
)ON [PRIMARY]
this is actually a script sql server 2008 created for me,
but when I look at the object explorer I see an ugly name for the index (something like PK_PnrDetai_CB394B1958F2C25C). How can I change it? If so?
While I agree with #marc_s that you should always declare these names up front, I disagree that you have to drop and re-create:
EXEC sp_rename 'PK_PnrDetai_CB394B1958F2C25C', 'my_new_shiny_name', OBJECT;
You can (and you should) explicitly give a name to your primary key constraint:
ALTER TABLE [dbo].[PnrDetails1]
ADD CONSTRAINT PK_PnrDetails1
PRIMARY KEY CLUSTERED([OId] ASC) ON [PRIMARY]
You can only do this at the time of creation - so in your case, you probably have to drop it first, and then re-create it with the proper, readable name.
Or use this, if the table already exists:
DECLARE #new_pk_name VARCHAR(MAX)='pk_new_name' --here set new name of primary key
DECLARE #table VARCHAR(MAX)='dbo.table_name' --here set name of the table
DECLARE #old_pk_name VARCHAR(MAX)
SELECT
#old_pk_name=name
FROM sys.key_constraints
WHERE [type] = 'PK'
AND [parent_object_id] = OBJECT_ID(#table);
SET #old_pk_name=#table+'.'+#old_pk_name;
EXEC sp_rename #old_pk_name, #new_pk_name;
GO

Considerations for updating a 'SiteVisit' row many times over a session

SQL Server 2005:
I have a SiteVisit row which contains information about a users visit, for instance HttpRefer, whether or not they placed an order, browser, etc.
Currently for reporting I am joining this table with SiteEvent which contains information about each 'section' visited. This then produces a view which shows statistics about how many sections each user visited. Obviously this is not a sustainable way to do this and now I'm doing some refactoring.
I'd like to move the SectionsVisited column from my View to an actual column in SiteVisit. I'd then update it everytime a user went to that session.
Now my actual question:
What kind of considerations do I need to take into account when updating a row many times per session. Obviously I have an index on the row (currently indexed by a GUID to prevent most malicious tampering).
I just want to know what non-obvious things I should do (if any). Are there any specific things I should do to optimize the table or will SQL server 2005 pretty much take care of itself
NB: it is a flash site so please dont just recommend a tracking tool. I want to do some
'crazy' datamining and have developed the tracking as such. This is primarily intended to be a database question not a question about 'how to track'.
Requested table definition:
USE [RazorSite]
GO
/****** Object: Table [dbo].[SiteVisit] Script Date: 10/29/2008 14:35:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[SiteVisit](
[SiteVisitId] [int] IDENTITY(1,1) NOT NULL,
[SiteUserId] [int] NULL,
[ClientGUID] [uniqueidentifier] ROWGUIDCOL NULL CONSTRAINT [DF_SiteVisit_ClientGUID] DEFAULT (newid()),
[ServerGUID] [uniqueidentifier] NULL,
[UserGUID] [uniqueidentifier] NULL,
[SiteId] [int] NOT NULL,
[EntryURL] [varchar](100) NULL,
[CampaignId] [varchar](50) NULL,
[Date] [datetime] NOT NULL,
[Cookie] [varchar](50) NULL,
[UserAgent] [varchar](255) NULL,
[Platform] [int] NULL,
[Referer] [varchar](255) NULL,
[RegisteredReferer] [int] NULL,
[FlashVersion] [varchar](20) NULL,
[SiteURL] [varchar](100) NULL,
[Email] [varchar](50) NULL,
[FlexSWZVersion] [varchar](20) NULL,
[HostAddress] [varchar](20) NULL,
[HostName] [varchar](100) NULL,
[InitialStageSize] [varchar](20) NULL,
[OrderId] [varchar](50) NULL,
[ScreenResolution] [varchar](50) NULL,
[TotalTimeOnSite] [int] NULL,
[CumulativeVisitCount] [int] NULL CONSTRAINT [DF_SiteVisit_CumulativeVisitCount] DEFAULT ((0)),
[ContentActivatedTime] [int] NULL CONSTRAINT [DF_SiteVisit_ContentActivatedTime] DEFAULT ((0)),
[ContentCompleteTime] [int] NULL,
[MasterVersion] [int] NULL CONSTRAINT [DF_SiteVisit_MasterVersion] DEFAULT ((0)),
CONSTRAINT [PK_SiteVisit] PRIMARY KEY CLUSTERED
(
[SiteVisitId] 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].[SiteVisit] WITH CHECK ADD CONSTRAINT [FK_SiteVisit_Platform] FOREIGN KEY([Platform])
REFERENCES [dbo].[Platform] ([PlatformId])
GO
ALTER TABLE [dbo].[SiteVisit] CHECK CONSTRAINT [FK_SiteVisit_Platform]
GO
ALTER TABLE [dbo].[SiteVisit] WITH CHECK ADD CONSTRAINT [FK_SiteVisit_Site] FOREIGN KEY([SiteId])
REFERENCES [dbo].[Site] ([SiteId])
GO
ALTER TABLE [dbo].[SiteVisit] CHECK CONSTRAINT [FK_SiteVisit_Site]
GO
ALTER TABLE [dbo].[SiteVisit] WITH CHECK ADD CONSTRAINT [FK_SiteVisit_SiteUser] FOREIGN KEY([SiteUserId])
REFERENCES [dbo].[SiteUser] ([SiteUserId])
GO
ALTER TABLE [dbo].[SiteVisit] CHECK CONSTRAINT [FK_SiteVisit_SiteUser]
Current indexes:
IX_CampaignId - non unique, non clustered
IX_ClientGUID - Unique, non clustered <-- this is how a user is identified for updates
IX_UserGUID - non unique, non clustered
PK_SiteVisit - (SiteVisitId column) - clustered
The best suggestion that I can give is: keep the table small.
How? Have one table that contains all "live" data, i.e. active sessions. When a session expires : move the data out to an "archive" table or even another database server to do your mining.
Have only very few indexes on the "live" table (session id). You can have all the indexes you want on the "archive" table for faster data retreival.