Add a new column to Table with exisiting primary key - sql

I am trying to add a new column(field) to a table with 4 columns and an extra id column.
But there seems to be a primary key restriction?
can someone help with this?
CREATE TABLE [dbo].[table1]( [id] [int] IDENTITY(1,1) NOT NULL, [a] [int] NOT NULL, [b]
[int] NOT NULL, [c] [int] NOT NULL, [d] [int] NOT NULL, [SCD_Date] [date] NOT NULL, [EndDate]
[date] NULL, CONSTRAINT [PK_table1] PRIMARY KEY CLUSTERED

You need to add the Primary Key in the constraint.
CREATE TABLE [dbo].[table1](
[id] [int] IDENTITY(1,1) NOT NULL,
[a] [int] NOT NULL,
[b] [int] NOT NULL,
[c] [int] NOT NULL,
[d] [int] NOT NULL,
[SCD_Date] [date] NOT NULL,
[EndDate]
[date] NULL,
CONSTRAINT [PK_table1] PRIMARY KEY CLUSTERED (id asc)
)

Related

Is there a way to do this, Not to repeat?

I handle projects by code (PROYECT_A A00001)
There are 3 tables (SEGMENT SE00001,LABLE LA00001,STRONG ST00001) that relate to a project, there may be repeated codes from these tables but they belong only to a project
Is there any way to not repeat the fields?
CREATE TABLE [dbo].[PROYECT_A](
[PROYECT_A] [int] IDENTITY(1,1) NOT NULL,
[CODE_A] AS ('A'+right('00000'+CONVERT([varchar],[PROYECT_A],(0)),(5))),
[STATUS] [datetime] NOT NULL,
[CREATION_DATE] [datetime] NOT NULL,
CONSTRAINT [PK_RR] PRIMARY KEY CLUSTERED
(
[CODE_A] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
CREATE TABLE [dbo].[SEGMENT](
[ID_SEGMENT] [int] IDENTITY(1,1) NOT NULL,
[CODE_SE] AS ('SE'+right('00000'+CONVERT([varchar],[ID_SEGMENT],(0)),(5))),
[NAME] [varchar](20),
[POWW] [varchar](20),
[SQWE] [varchar](20),
[DATESTART] [datetime] NOT NULL,
[DATESTART] [datetime] NOT NULL
[CODE_A] [varchar](20)
GO
CREATE TABLE [dbo].[LABLE](
[ID_LABLE] [int] IDENTITY(1,1) NOT NULL,
[CODE_LA] AS ('LA'+right('00000'+CONVERT([varchar],[ID_LABLE],(0)),(5))),
[NAME] [varchar](20),
[POWW] [varchar](20),
[SQWE] [varchar](20),
[DATESTART] [datetime] NOT NULL,
[DATESTART] [datetime] NOT NULL
[CODE_A] [varchar](20)
GO
CREATE TABLE [dbo].[STRONG](
[ID_STRONG] [int] IDENTITY(1,1) NOT NULL,
[CODE_ST] AS ('ST'+right('00000'+CONVERT([varchar],[ID_STRONG],(0)),(5))),
[NAME] [varchar](20),
[POWW] [varchar](20),
[SQWE] [varchar](20),
[DATESTART] [datetime] NOT NULL,
[DATESTART] [datetime] NOT NULL
[CODE_A] [varchar](20)
GO
create a single table with Type column to differentiate the records whether it belongs to SEGMENT,LABLE or STRONG.
CREATE TABLE [dbo].[SEGMENT](
[ID_SEGMENT] [int] IDENTITY(1,1) NOT NULL,
[Type] as Varchar(15) -- Here `SEGMENT`,`LABLE` or `STRONG`
[CODE_SE] AS (case type
when 'Segment' then 'SE'
when 'LABLE' then 'LA'
else 'ST'
end +right('00000'+CONVERT([varchar],[ID_SEGMENT],(0)),(5))),
[NAME] [varchar](20),
[POWW] [varchar](20),
[SQWE] [varchar](20),
[DATESTART] [datetime] NOT NULL,
[DATESTART] [datetime] NOT NULL
[CODE_A] [varchar](20)
)

SQL Server partition and index

I have a requirement to design a table that is going to have around 80 million records. I created a partition for every month using persisted column (if its wrong suggest me the best way). Please find below scripts that I used to create tables and partition and the query that's going to be used often. Only Insertion and deletion will be done on this table.
-- Create the Partition Function
CREATE PARTITION FUNCTION PF_Invoice_item (int)
AS RANGE LEFT FOR VALUES (1,2,3,4,5,6,7,8,9,10,11,12);
-- Create the Partition Scheme
CREATE PARTITION SCHEME PS_Invoice_item
AS PARTITION PF_Invoice_item ALL TO ([Primary]);
CREATE TABLE [Invoice]
(
[invoice_id] [bigint] NOT NULL,
[Invoice_Number] [varchar](255) NULL,
[Invoice_Date] [date] NULL,
[Invoice_Total] [numeric](18, 2) NULL,
[Outstanding_Balance] [decimal](18, 2) NULL,
CONSTRAINT [PK_Invoice_id] PRIMARY KEY CLUSTERED([invoice_id] ASC)
)
CREATE TABLE [InvoiceItem](
[invoice_item_id] [bigint] NOT NULL,
[invoice_id] [bigint] NOT NULL,
[invoice_Date] [date] NULL,
[make] [varchar](255) NULL,
[serial_number] [varchar](255) NULL,
[asset_id] [varchar](100) NULL,
[application] [varchar](255) NULL,
[customer] [varchar](255) NULL,
[ucid] [varchar](255) NULL,
[dcn] [varchar](255) NULL,
[dcn_name] [varchar](255) NULL,
[device_serial_number] [varchar](255) NULL,
[subscription_name] [varchar](255) NULL,
[product_name] [varchar](255) NULL,
[subscription_start_date] [date] NULL,
[subscription_end_date] [date] NULL,
[duration] [varchar](50) NULL,
[promo_name] [varchar](255) NULL,
[promo_end_date] [date] NULL,
[discount] [decimal](18, 2) NULL,
[tax] [decimal](18, 2) NULL,
[line_item_total] [decimal](18, 2) NULL,
[mth] AS (datepart(month,[invoice_date])) PERSISTED NOT NULL,**
[RELATED_PRODUCT_RATEPLAN_NAME] [varchar](250) NULL,
[SUB_TOTAL] [decimal](18, 2) NULL,
[BILLING_START_DATE] [date] NULL,`enter code here`
[BILLING_END_DATE] [date] NULL,
[SUBSCRIPTION_ID] [varchar](200) NULL,
[DEVICE_TYPE] [varchar](200) NULL,
[BASE_OR_PROMO] [varchar](200) NULL,
CONSTRAINT [PK_InvoiceItem_ID] PRIMARY KEY CLUSTERED ([invoice_item_id]
ASC,[mth] ASC))
ON PS_Invoice_item(mth);
GO
ALTER TABLE [InvoiceItem] WITH CHECK ADD CONSTRAINT [FK_Invoice_ID]
FOREIGN KEY([invoice_id])
REFERENCES [Invoice] ([invoice_id])
GO
I will be using below queries
select subscription_name,duration,start_date,end_date,promotion_name,
promotion_end_date,sub_total,discount,tax,line_item_total from InvoiceItem
lt inner join Invoice on lt.invoice_id=invoice.invoice_id where
invoice.invoice_number='' and lt.customer='' and lt.ucid='' lt.make='' and
lt.SERIAL_NUMBER='' and lt.dcn='' and lt.application=''
select customer,make,application from billing.AssetApplicationTotals
lineItem inner join billing.Invoice invoice on
lineItem.invoice_id=invoice.invoice_id where invoice.invoice_number='';
SELECT [invoice_Date],[make],[serial_number],[application],[customer],
[ucid],[dcn],[dcn_name],[device_serial_number]
,[subscription_name],[product_name],[subscription_start_date],
[subscription_end_date],[duration],[promo_name],[promo_end_date]
FROM [InvoiceItem] where [application]=''
SELECT [invoice_Date],[make],[serial_number],[application],[customer],
[ucid],[dcn],[dcn_name],[device_serial_number]
,[subscription_name],[product_name],[subscription_start_date],
[subscription_end_date],[duration],[promo_name],[promo_end_date]
FROM [InvoiceItem] where [customer]=''
What is the best way to create index? Shall I create separate non clustered index for each filter, or shall I have Composite index and shall I have covering index to avoid key lookup?

create table fails in loop (SQL Server)

I have a sql script that creates tables for each db in my sql server. However it fails on one create table script. Eg the
CREATE TABLE [dbo].[Mx_Poll_Tags]
command. What is wrong with this? I don't see it.
The weird part is when I one by one run the scripts in a query window they all work fine. Only is this particular proc it fails.
The error states:
Msg 173, Level 15, State 1, Line 71
The definition for column 'Unit' must include a data type.
The create script is made by SQL Server itself by scripting an existing Mx_Poll_Tags table as CreateTo.
Does anyone see what the error is?
BEGIN
declare #proc nvarchar(max)
set #proc='if ''?'' like ''Client_%''
begin
use [?]
print ''?''
DROP TABLE [dbo].[ManualMetersInput]
DROP TABLE [dbo].[ManualMeterActions]
DROP TABLE [dbo].[ManualMeters]
DROP TABLE [dbo].[MX_Poll]
--DROP TABLE [dbo].[Mx_Poll_Tags]
DROP TABLE [dbo].[MX_Poll_Info]
DROP TABLE [dbo].[MX_Poll_Logs]
DROP TABLE [dbo].[MX_Poll_QA]
--DROP TABLE [dbo].[MX_Poll_Vars]
CREATE TABLE [dbo].[ManualMeters]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Ean] [varchar](max) NULL,
[Period] [int] NULL,
[TagTable] [varchar](max) NULL,
[TagTableId] [varchar](max) NOT NULL,
[Overflow] [int] NULL,
[TZ] [varchar](max) NULL,
) ON [PRIMARY]
CREATE TABLE [dbo].[ManualMetersInput]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Timestamp] [datetime2](7) NOT NULL,
[ManualMeterId] [int] NOT NULL,
[Value] [decimal](18, 3) NOT NULL,
[IsOverflow] [bit] NOT NULL,
[ImportDate] [datetime2](7) NOT NULL,
) ON [PRIMARY]
CREATE TABLE [dbo].[ManualMeterActions]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[ManualMeterId] [int] NOT NULL,
[UserId] [int] NOT NULL,
[Type] [nvarchar](max) NOT NULL,
) ON [PRIMARY]
CREATE TABLE [dbo].[MX_Poll]
(
[timestamp] [datetime2](7) NOT NULL,
[localtimestamp] [datetime2](7) NOT NULL,
) ON [PRIMARY]
CREATE TABLE [dbo].[MX_Poll_Info]
(
[timestamp] [datetime2](7) NOT NULL,
[info] [nvarchar](max) NOT NULL,
) ON [PRIMARY]
CREATE TABLE [dbo].[MX_Poll_Logs]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[timestamp] [datetime2](7) NOT NULL,
[Message] [nvarchar](max) NULL,
) ON [PRIMARY]
CREATE TABLE [dbo].[MX_Poll_QA]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[timestamp] [datetime2](7) NOT NULL,
[tag] [nvarchar](max) NULL,
[QA] [int] NULL
) ON [PRIMARY]
-- error here
CREATE TABLE [dbo].[Mx_Poll_Tags]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](800) NOT NULL,
[Unit] [int] NOT NULL,
[FieldName] [nvarchar](100) NULL,
[ScaleFromMin] [decimal](18, 3) NULL,
[ScaleFromMax] [decimal](18, 3) NULL,
[ScaleToMin] [decimal](18, 3) NULL,
[ScaleToMax] [decimal](18, 3) NULL,
[DeltaOfKwhCounter_Id] [int] NULL,
[Visible] [int] NULL,
[Type] [nvarchar](50) NULL,
[Enable] [int] NULL,
[Content] [int] NULL,
[Quantity] [int] NULL,
[Signal] [int] NULL,
[SignalDescription] [nvarchar](max) NULL,
[Connection] [nvarchar](max) NULL,
[Cable] [nvarchar](max) NULL,
[Comments] [nvarchar](max) NULL,
[UsedForPrediction_0] [bit] NOT NULL,
[RelatedToPrediction_0] [bit] NOT NULL,
[CalculatedByPredictionNo] [int] NULL,
) ON [PRIMARY]
end';
--print #proc;
exec sp_MSForEachDB #proc
END
GO
Can you try it with just creating that table?
Also, can you eliminate the "begin" and "end"? Based on this thread: http://www.sqlservercentral.com/Forums/Topic808714-8-1.aspx
I don't have enough reputation to make this a comment.
EDIT:
By default, sys.sp_MSforeachdb #command1 has a parameter length of nvarchar(2000). Even though you're passing in a varchar(max), anything over 2000 is being truncated.

how to prefix identity column character in msSQL

How can I alter a table's primary identity column to include a letter before the number? I have a table named vendor_master with a primary key VendorID that I would like to store as v1,v2,v3 and so on
CREATE TABLE [dbo].[vendor_master](
[vendorID] [int] IDENTITY(1,1) NOT NULL,
[Vname] [nvarchar](50) NOT NULL,
[Email] [nvarchar](50) NOT NULL,
[Mobile] [bigint] NULL,
[Landline] [bigint] NULL,
[Address] [nvarchar](max) NOT NULL,
[Pincode] [int] NOT NULL)
If it's important to you to have the field in your table, try the following:
CREATE TABLE [dbo].[vendor_master]
(
[vendorID] [int] IDENTITY(1,1) NOT NULL,
[Vname] [nvarchar](50) NOT NULL,
[Email] [nvarchar](50) NOT NULL,
[Mobile] [bigint] NULL,
[Landline] [bigint] NULL,
[Address] [nvarchar](max) NOT NULL,
[Pincode] [int] NOT NULL,
[VendorKey] AS ('v' +CONVERT([varchar](10),[vendorID])) PERSISTED
)
Of course, that will yield you some weird results when sorting, so you might consider padding the data with zeroes to make it a consistent length:
CREATE TABLE [dbo].[vendor_master]
(
[vendorID] [int] IDENTITY(1,1) NOT NULL,
[Vname] [nvarchar](50) NOT NULL,
[Email] [nvarchar](50) NOT NULL,
[Mobile] [bigint] NULL,
[Landline] [bigint] NULL,
[Address] [nvarchar](max) NOT NULL,
[Pincode] [int] NOT NULL,
[VendorKey] AS ('v' +RIGHT('000000000' + CONVERT([varchar](10),[vendorID]),10)) PERSISTED
)
You can't actually do what you are asking. Anyway, there is no reason to add the same letter to the front of a fields value. Instead add the letter in your SELECT statment:
SELECT CONCAT('v', vendorID) AS VendorIDWithPrefix, Vname, Email, Mobile
FROM vendor_master

SQL query taking 1 minute and 35 seconds

I am executing the query on SQL server on hosting and it is taking 1 minute and 35 seconds. And the no, of rows of retrieval are 18000. Still it is taking too much time. Query is
select ID,
FirstName,
LastName,
Branch,
EnquiryID,
Course,
College,
Mobile,
ExamID,
EntranceID,
Entrance,
Venue,
RegNo,
VenueID,
Exam,
Gender,
row_number() over (partition by EnquiryID order by ID asc) as AttemptNO
from AGAM_View_AOPList
order by EnquiryID
TABLE SCHEMAS
CREATE TABLE [dbo].[AGAM_AceOFPace](
[ID] [int] IDENTITY(1,1) NOT NULL,
[EnquiryID] [int] NULL,
[FirstName] [nvarchar](100) NULL,
[MiddleName] [nvarchar](100) NULL,
[LastName] [nvarchar](100) NULL,
[BranchID] [int] NULL,
[Branch] [nvarchar](100) NULL,
[CourseID] [int] NULL,
[ExamID] [int] NULL,
[Exam] [nvarchar](200) NULL,
[EntranceID] [int] NULL,
[Entrance] [nvarchar](200) NULL,
[RegNo] [nvarchar](200) NULL,
[EntranceCode] [nvarchar](100) NULL,
[ExamDate] [nvarchar](50) NULL,
[UserID] [nvarchar](100) NULL,
[EntranceFees] [numeric](18, 2) NULL,
[VenueID] [int] NULL,
[Venue] [nvarchar](max) NULL,
[ChequeNumber] [nvarchar](50) NULL,
[Bank] [nvarchar](100) NULL,
[CreatedDate] [datetime] NULL,
CONSTRAINT [PK_AGAM_AceOFPace] 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].[AGAM_AceOFPace] WITH CHECK ADD CONSTRAINT [FK_AGAM_AceOFPace_AGAM_Inquiry] FOREIGN KEY([EnquiryID])
REFERENCES [dbo].[AGAM_Inquiry] ([ID])
GO
ALTER TABLE [dbo].[AGAM_AceOFPace] CHECK CONSTRAINT [FK_AGAM_AceOFPace_AGAM_Inquiry]
GO
SECOND TABLE
CREATE TABLE [dbo].[AGAM_Inquiry](
[ID] [int] IDENTITY(1,1) NOT NULL,
[RegNo] [nvarchar](200) NULL,
[BranchID] [int] NULL,
[Category] [nvarchar](100) NULL,
[CourseID] [int] NULL,
[EntranceFees] [numeric](18, 2) NULL,
[EntranceID] [int] NULL,
[UserID] [nvarchar](50) NULL,
[Status] [nvarchar](50) NULL,
[ReminderDate] [datetime] NULL,
[Reminder] [nvarchar](150) NULL,
[Mobile] [nvarchar](50) NULL,
[Email] [nvarchar](50) NULL,
[FirstName] [nvarchar](50) NULL,
[MiddleName] [nvarchar](50) NULL,
[LastName] [nvarchar](50) NULL,
[Landline] [nvarchar](50) NULL,
[Address] [nvarchar](100) NULL,
[DOB] [datetime] NULL,
[Gender] [nvarchar](50) NULL,
[PfBatchTime] [nvarchar](50) NULL,
[SourceOfInquiry] [nvarchar](50) NULL,
[ExStudentID] [int] NULL,
[InquiryDate] [datetime] NULL,
[ReceiptNumber] [nvarchar](50) NULL,
[RawID] [int] NULL,
[Deleted] [int] NULL,
[CreatedBy] [nvarchar](50) NULL,
[CreatedDate] [datetime] NULL,
[LastModifiedBy] [nvarchar](50) NULL,
[LastModifiedDate] [datetime] NULL,
[College] [nvarchar](150) NULL,
[Qualification] [nvarchar](150) NULL,
[RptNo] [nvarchar](100) NULL,
CONSTRAINT [PK_AGAM_Inquiry] 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].[AGAM_Inquiry] WITH CHECK ADD CONSTRAINT [FK_AGAM_Inquiry_AGAM_Branch] FOREIGN KEY([BranchID])
REFERENCES [dbo].[AGAM_Branch] ([ID])
GO
ALTER TABLE [dbo].[AGAM_Inquiry] CHECK CONSTRAINT [FK_AGAM_Inquiry_AGAM_Branch]
GO
ALTER TABLE [dbo].[AGAM_Inquiry] WITH CHECK ADD CONSTRAINT [FK_AGAM_Inquiry_AGAM_Course] FOREIGN KEY([CourseID])
REFERENCES [dbo].[AGAM_Course] ([ID])
GO
ALTER TABLE [dbo].[AGAM_Inquiry] CHECK CONSTRAINT [FK_AGAM_Inquiry_AGAM_Course]
GO
ALTER TABLE [dbo].[AGAM_Inquiry] WITH CHECK ADD CONSTRAINT [FK_AGAM_Inquiry_AGAM_Users] FOREIGN KEY([UserID])
REFERENCES [dbo].[AGAM_Users] ([UserID])
GO
ALTER TABLE [dbo].[AGAM_Inquiry] CHECK CONSTRAINT [FK_AGAM_Inquiry_AGAM_Users]
GO
Can you try with changing the view to this?
SELECT TOP (100) PERCENT
AP.ID,
AP.FirstName,
AP.LastName,
AP.Branch,
AP.EnquiryID,
AC.Name,
AI.College,
AI.Mobile,
AP.ExamID,
AP.EntranceID,
AP.RegNo,
AP.VenueID,
AP.Exam,
AI.Gender,
AP.BranchID,
AP.CourseID,
AP.CreatedDate,
AI.Status,
AP.Entrance,
AP.Venue
FROM dbo.AGAM_AceOFPace AS AP
INNER JOIN dbo.AGAM_Inquiry AS AI ON AI.ID = AP.EnquiryID
INNER JOIN dbo.AGAM_Course as AC on AC.ID = AP.CourseId
ORDER BY AP.EnquiryID
Do you have an index on EnquiryId and CourseID?
Seeing as you are joining, ordering and partitioning by it you really should.
CREATE INDEX IDX_AGAM_AceOFPace_EnquiryID
ON AGAM_AceOFPace (EnquiryID)
CREATE INDEX IDX_AGAM_AceOFPace_CourseID
ON AGAM_AceOFPace (CourseID)