Unique constraint using SQL Server CAST([column] AS DATE) function - sql

I have an appointments table that has (among others) a [personid] and an [appdate] column of datetime(2) datatype. I want to add a constraint that will prevent any personid from getting more than one appointment on any single day.
I tried this but it did not work
ALTER TABLE dbo.tblappointments
ADD CONSTRAINT SingleApp UNIQUE (PersonID, CAST(Appdate AS DATE))
Thank you.

I imagine you can create a computed column and use it as the index.
ALTER TABLE dbo.tblappointments ADD AppointmentDay as CAST(Appdate AS DATE) PERSISTED
If you don't use PERSISTED the value will be calculated every time the column is accessed

Related

Autogenerated timestamp column( primary key) to existing table DB2

Is it possible to add an autogenerated primary key column ( timestamp) to the existing table with alter table?
Something like this but it doesn't compile
ALTER TABLE DB2ADMIN.xxxyyyy ADD COLUMN ID TIMESTAMP NOT NULL WITH DEFAULT timestamp(generate_unique())#
Error during Prepare
42601(-104)[IBM][CLI Driver][DB2/AIX64] SQL0104N An unexpected token "timestamp" was found following "OT NULL WITH DEFAULT". Expected tokens may include: "CHECK". SQLSTATE=42601
It is unwise to use a fake (from generate_unique) timestamp datatype as a primary key because it makes setting values for pre-existing rows more awkward, and makes date arithmetic impossible.
The datatype TIMESTAMP is better suited for real dates/times because then you can use date arithmetic, which is practical for business. If the values in your fake timestamp-column are from generate-unique then you cannot sensibly use date arithmetic.
If you try to use a real timestamp value , (instead of generate_unique) , such as current timestamp then you are likely to get collisions, depending on the insert-rate. Usually that's a bad idea. Also this makes setting values for any pre-existing rows more difficult.
It is usually much easier and faster to use an autogenerated identity column as a surrogate primary key, especially if the table already has existing data.
Here is a typical way to do this which works with Db2-LUW and also on older versions of Db2. Other ways are possible with later versions of Db2.
Firs you need to verify that the table does not already have a primary key, as there can only be at most one of these per table.
Next, check if the table already has a unique index on a NOT NULL column, because if such a column exists then it can be promoted to be the primary key column.
If neither of the above exist, then you can use logic like this below to add an autgenerated column, set unique values in any existing rows, and ensure that any future inserts automatically get a unique value in the column without application intervention.
alter table myschema.mytab add column id bigint not null default 0 ;
alter table myschema.mytab alter column id drop default ;
alter table myschema.mytab alter column id set generated always as identity ;
update myschema.mytab set id = default ;
alter table myschema.mytab add constraint pkey primary key(id) ;
reorg table myschema.mytab ;
runstats on table myschema.mytab with distribution and detailed indexes all;
You can use CURRENT_TIMESTAMP instead of timestamp(generate_unique())
ALTER TABLE sellers ADD COLUMN ID TIMESTAMP NOT NULL WITH DEFAULT CURRENT_TIMESTAMP
You can test here

How to use only the year of a DateTime column in a SQL Unique Constrain?

Im creating a Unique constraint, that only allows to use the a Registry number per year,
with this i mean that can exist more that one number 2, in the registry but only if this
were created on different years. I have heard that it is possible to do ir with the Unique
constraint but i do not know how, without needing to create a column for year and another for month, and ect.
Query
ALTER TABLE dbo.correspondencia_FFAA
ADD CONSTRAINT uk_correspondecia UNIQUE (num_corres, fecha_cre);
num_corres is the Registry Number, and fecha_cre is the Creation Date, but i only need the year not the whole column, is it possible
Thanks
Use a computed column and then created the index. Something like:
alter table registry add RegistryYear as year(RegistryDate);
create index registry_number_year on Registry(number, RegistryYear);
Well, in SQL Server, there's a datatype called "DATE" - you could use that column and create an index on that.
You could of course also add a computed column of type "DATE" to your table and just fill the date portion of the DATETIME column into that computed column, make it PERSISTED, and index it. Should work just fine!
ALTER TABLE dbo.Entries
ADD yearOnly as Year(CAST(CompositionDate AS DATE)) PERSISTED
CREATE UNIQUE INDEX UX_Entries ON Entries(yearOnly , Slug)

SSIS Lookup multiple dates in my fact table, how to pull this off using one date dimension?

In my SSIS/DW project, I have a DIM.DATE dimension which is linked to my FACT table by a surrogate key as follows:
ALTER TABLE FACT.SALES ADD date_id INT NOT NULL
ALTER TABLE FACT.SALES WITH CHECK ADD CONSTRAINT FK_dim_date FOREIGN KEY (date_id) REFERENCES DIM.DATE(date_id)
This creates a "date_id" in my fact table, now during my SSIS import process I have a date column being passed (shipped_date), I use this to look up the DIM.DATE table and pass in the surrogate key in my dimension.
This works great, but now I need to have a few different date dimensions for invoice date, received date, etc.
I am confused as to how to make use of the existing DIM.DATE to do this?
I could then add more columns into my fact table..
-- add column into fact table
ALTER TABLE FACT.SALES ADD shipped_date_id INT NOT NULL
ALTER TABLE FACT.SALES ADD invoice_date_id INT NOT NULL
-- add foreign key
ALTER TABLE FACT.SALES WITH CHECK ADD CONSTRAINT FK_shipped_date FOREIGN KEY (shipped_date_id) REFERENCES DIM.DATE(date_id)
ALTER TABLE FACT.SALES WITH CHECK ADD CONSTRAINT FK_invoice_date FOREIGN KEY (invoice_date_id) REFERENCES DIM.DATE(date_id)
But when I do my lookup, I can only pass in the "date_id" column.. I am confused how to make this work all together.
Anyone able to clear this up for me?
You have to use multiple LookUp transforms... 1 for each DateKey field in the fact table.

SQL: Create new column with default, unique value

I have added a new column, called Ordinal, to a table called Activity. The problem is that I gave it a UNIQUE constraint, set it to allow NULL (though this I won't want in the end.. I just needed to set it to that to get a little farther with the script), and did not give it a default value. I'm now running a RedGate SQL Compare script that was generated by comparing this table to a version of the Activity table that does not have the column. But I'm getting the following error:
The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'iwt.Activity' and the index name 'IX_Activity'. The duplicate key value is (1).
So based on my research, it's trying to create a unique key constraint on the Ordinal column, but NULL is not unique. So my next step was to give it a unique value of 1 just to let the script pass. But 1 isn't going to be unique either. So, finally, my question:
Preferably in SQL Server Management Studio, how do I set a column as having a unique default value? Isn't that what I would need to create this constraint?
Thanks.
try this:
NULL will be the first constraint when you create the column.
UNIQUE will be as add constraint, you should add the second constraint.
they can run on this order with no problem (tested):
--first constraint
alter table Table_Name
add Column_Name int null
--second constraint
alter table Table_Name
add constraint Constraint_Name unique (Column_Name)
In my example :
PaymentGatewayHash is column
Cart is a table
--first query
alter table Cart
add PaymentGatewayHash NVARCHAR(20) null
--second query
CREATE UNIQUE INDEX PaymentGatewayHashUnique
ON Cart (PaymentGatewayHash)
WHERE PaymentGatewayHash IS NOT NULL
I just tested that :D

Table without a identity column but this column can't have repeated values

I'm creating a table that needs to have 2 columns. The first column can't be repeated. The thing is, I will insert the value of the first column. How do I create this column?
SQLServer 2005
Make the first column the primary key of the table.
Set the column as a primary key. I doesn't have to be an identity column to has a PK.
Create it the same way you would any other column: create table sometable (column1 varchar(10), column2 varchar(20)) or whatever.
Do you mean: How can you get the database to force it to be unique? Either declare it to be the primary key, or create a unique index on the column.
Perhaps you're thinking that a primary key must be auto-generated? There's no such rule. Whether you invent the value yourself or use an autonumber feature has nothing to do with whether a field can be a primary key.
Why not just put a unique constraint on it:
ALTER TABLE <table_name>
ADD CONSTRAINT <constraint_name>
UNIQUE(<column_name>)