Storing hex equivalent in identity column in sql - sql-server

Just as the title says, if I have a table has a struct like this
create table myTable
(
ID int identity(1,1) not null,
col1 varchar(20) not null,
col2 varchar(20) not null
constraint pk_myTable primary key (ID)
)
If I insert some value in this table it would automatically take value in col ID. I wanna know is a way I could get SQL Server to store hex equivalent in the column. Say, for 1, it should store 0x01 2 as 0x02... 10 as 0xA and so on?
I don't wanna know any tricks or something, I know I can create this this col as varchar and then create a procedure for insert, or create a trigger for insert, that would do the required transformation and would produce the desired result, that's not a big issue.
But what I wanna know is there a inbuilt function/procedure/trigger that would help me achieve what I am trying to achieve? Not necessarily in SQL Server 2008, but may be in 2012, does there exists anything like this?

I agree with Joe Stefanelli and Habo above that you don't need do do this. That said the technique is usefull in other scenarios.
Define your table like this (note the computed column)
CREATE TABLE mytable(
ID int identity(1,1) not null,
col1 varchar(20) not null,
col2 varchar(20) not null,
ComputedHexColumn AS CONVERT(VARBINARY(8), ID),
CONSTRAINT pk_myTable PRIMARY KEY CLUSTERED(ID)
)
Then populate it
INSERT INTO mytable(col1,col2)
SELECT 'col1 - 1','col2 - 1'
UNION SELECT 'col1 - 2','col2 - 2'
UNION SELECT 'col1 - 3','col2 - 3'
UNION SELECT 'col1 - 4','col2 - 4'
then anytime you select from the table it will include the hex value
SELECT * FROM mytable
In cases where the computed value was much more expensive to calculate then you can mark the column as PERSISTED. The database will then physically store the value and update it when appropriate.

Related

Partition SQL Server tables based on column not in the primary key?

Let's say I have a table like this:
create table test_partitions
(
pk_id int not null,
col1 nvarchar(20),
col2 nvarchar(100),
constraint pk_test_partitions primary key (pk_id, col1)
);
I want to partition this table to improve query performance so that I don't have to look through the whole table every time I need something. So I added a calculated column:
create table test_partitions
(
pk_id int not null,
partition_id as pk_id % 10 persisted not null,
col1 nvarchar(20),
col2 nvarchar(100),
constraint pk_test_partitions primary key (pk_id, col1)
);
So ever time I do select * from test_partitions where pk_id = 123 I want SQL Server to look in only 1/10th of the entire table. I don't want to add partition_id column to the primary key because it will never be part of the where clause. How do I partition my table on partition_id?
Just right now i did test and found a solution
SELECT TOP ((SELECT COUNT(*) [TABLE_NAME])/10)
* FROM [TABLE_NAME]
it returns 1/10th of your records
To improve your query performance you can apply pagination. That is you can use fetch next query to achieve your output.
Please go through this for more details.
SELECT column-names FROM table-name
ORDER BY column-names
OFFSET n ROWS
FETCH NEXT m ROWS ONLY

SQL Server : identity and autoincrement for varchar

This is my first question on this platform. I am working on a database project. I want to use autoincrement for my primary key for id, but also want to add an alphabet before it. Are there other ways to do it apart from using 2 columns declaring one as identity and casting the other? I have worked with stored procedures and triggers.
Thank you
PS: I want to do it using one column if possible
You won't be able to do this with just one column.
The best solution is to use
an ID INT IDENTITY(1,1) column to get SQL Server to handle the automatic increment of your numeric value
a computed, persisted column to convert that numeric value to the value you need
So try this:
CREATE TABLE dbo.tblCompany
(
ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
CompanyID AS 'CMP-' + RIGHT('00000' + CAST(ID AS VARCHAR(5)), 5) PERSISTED,
.... your other columns here....
)
Now, every time you insert a row into tblCompany without specifying values for ID or CompanyID:
INSERT INTO dbo.tblCompany(Col1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
then SQL Server will increase your ID value, and CompanyID will contain values like CMP-00001, CMP-00002,...... and so on - automatically. The CompanyID column will be fill automatically, by SQL Server, upon inserting a new row - so there's no need for triggers or stored procedures or anything else - just this declaration in your table definition.
UPDATE: if you're using SQL Server 2012 or newer, you can do it with just one column - if you also create a SEQUENCE - like this:
CREATE SEQUENCE SEQ_CompanyID
AS INT
START WITH 1000
INCREMENT BY 1;
CREATE TABLE dbo.Company
(
CompanyID VARCHAR(20) NOT NULL
CONSTRAINT DF_CompanyID
DEFAULT('CMP-' + CAST(NEXT VALUE FOR dbo.SEQ_CompanyID AS VARCHAR(10))),
CompanyName VARCHAR(100) NOT NULL,
----- other columns here
)
Now if you make sure to insert with omitting the CompanyID column in the insert statement, like this:
INSERT INTO dbo.Company (CompanyName)
VALUES ('Company #1'), ('Company ABC'), ('Company Three');
then you get CMP-1001', 'CMP-1002 etc. as your CompanyID, again, automatically handled by SQL Server upon inserting a new row.

How to auto increment in vb form

I am using vb.net and SQL Server as backend; I want to auto generate id which is created as primary key and is there any way to auto generate id with alphanumeric ex:- cx10001,cx1002
The best solution is to use
an ID INT IDENTITY(1,1) column to get SQL Server to handle the automatic increment of your numeric value
a computed, persisted column to convert that numeric value to the value you need
So try this:
CREATE TABLE dbo.YourTable
(
ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
YourOtherId AS 'cx' + RIGHT('00000' + CAST(ID AS VARCHAR(5)), 5) PERSISTED,
.... your other columns here....
)
Now, every time you insert a row into YourTable without specifying values for ID or YourOtherID:
INSERT INTO dbo.YourTable(Col1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
then SQL Server will automatically and safely increase your ID value, and YourOtherID will contain values like cx00001, cx00002,...... and so on - automatically, safely, reliably, no duplicates.

Autoincrement of primary key column with varchar datatype in it

CREATE TABLE Persons
(
P_Id varchar(6) NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
PRIMARY KEY (P_Id)
)
in this table P_Id is the primary key. We want to generate autoincrement of P_Id with default value (PN00) in the start while inserting only LastName and FirstName .eg :-PN001 for first entry ,PN002 for second,PN003 for third and so on .
The only viable solution is to use
an ID INT IDENTITY(1,1) column to get SQL Server to handle the automatic increment of your numeric value
a computed, persisted column to convert that numeric value to the value you need
So try this:
CREATE TABLE dbo.Persons
(ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
P_ID AS 'PN' + RIGHT('00000' + CAST(ID AS VARCHAR(5)), 5) PERSISTED,
.... your other columns here....
)
Now, every time you insert a row into Persons without specifying values for ID or P_ID:
INSERT INTO dbo.Persons(Col1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
then SQL Server will automatically and safely increase your ID value, and P_Id will contain values like PN00001, PN00002,...... and so on - automatically, safely, reliably, no duplicates.
There are different ways to address your issue.
You could use a Trigger.Triggers are activated on some events. You could create a trigger for 'Instead of Insert On Persons' event. When the event is triggered, then generate a new P_Id. Insert this new P_Id alongwith all the values as the new record for your table.
This approach wont have coupling with the table's schema.
Refer this link for more information on Triggers :
https://msdn.microsoft.com/en-IN/library/ms189799.aspx
Refer this link to emulate 'before insert trigger' in SQL Server:
How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritence) entities?
You could also use a Procedure like :
create procedure Persons_insert(#lastname varchar(255), #firstname varchar(255))
as
begin
--write code to generate the ID as you like
insert into Persons(p_id,lastname,firstname)values(generated_id,lastname,firstname);
end

two digit year as primary key in sql server

I have a table with these columns:
ID int,
d date
Now what I need is to define the primary key in such a way that ID would be unique for each year; meaning that there can not be two same IDs in 2004, but it is possible to have two same IDs in two different years.
Like:
insert into myTable values(1, '1-1-2004'), (1, '1-1-2005')
but not like:
insert into myTable values(1, '3-1-2005'), (1, '1-1-2005')
I tried this:
primary key(ID, datepart(YY, d))
but I get syntax error.
One way of doing this, if you can alter the table structure, is to add a persisted computed column for the year part, and then add a primary key for (id, computer_col), like this:
CREATE TABLE myTable (
id INT NOT NULL,
d DATE NOT NULL,
y AS DATEPART(YEAR,d) PERSISTED NOT NULL,
PRIMARY KEY(id,y)
)
I'm not saying this is a good solution in any way, but it should work. Using a trigger on insert or a check constraint might be better.
Using your test data this will allow the first insert statement, but disallow the second as it violates the primary key constraint.

Resources