在字符和数字之间建立主键混合 [英] Making a Primary key mixture between characters and numbers
问题描述
我想创建一个名为student的表,其中包含如下主键:
STD-1对于第一个条目,第二个条目的STD-2等等。
我尝试了以下代码:
create table 学生
(
SID int 身份( 1 , 1 ),
STID as ' SID - ' + Cast(SID as Varchar ( 10 ))PERSISTED PRIMARY KEY ,
名称 varchar ( 20 )不 null ,
City varchar ( 30 )不 null ,
电话 varchar (< span class =code-digit> 10 )不 null
) ;
但它只适用于SQL Server Express而不是紧凑版。
有没有办法编写类似于它的代码来处理压缩版?
SqlCE不支持计算列,因此您必须在外部代码中执行此操作。 / blockquote>
我不建议你使用字符串列作为主键。
为什么:如果你保持性能会更好一个int主键(SID)。您仍然可以为计算值设置一列,可以在表格中设置唯一值=>你将保持所需的功能。但是你可以使用int主键在这个表上进行更高效的搜索和连接。
为了回答你的问题,这里是SQL Compact的版本:
创建 表学生
(
SID int PRIMARY KEY IDENTITY ( 1 , 1 ) ,
STID nvarchar ( 14 )) UNIQUE NOT NULL ,
名称 nvarchar ( 20 ) NOT NULL ,
City nvarchar (30 ) NOT NULL ,
电话 varchar ( 10 ) NOT NULL
);
但是,因为它被告知对于SQL Server Compact,您必须在代码中处理STID值的创建,因为数据库引擎无法为您处理。类似于:
Student.STID = string .Format( SID- {0},student.SID);
希望这有帮助。
Hi,
I would like to make a table called student that has a primary key like the following:
STD-1 for the first entry , STD-2 for the 2nd entry, etc.
I tried the following code:create table Student ( SID int identity (1,1), STID as 'SID-'+Cast(SID as Varchar(10)) PERSISTED PRIMARY KEY, Name varchar(20) not null, City varchar(30) not null, Phone varchar(10) not null );
But it only works with SQL server Express not with the compact edition.
Is there a way to write a code similar to it to work on compact edition?解决方案SqlCE does not support Computed Columns, so you will have to do this in your external code.
I do not recommend you to use a string column as your primary key.
Why : performance will be better if you keep an int primary key (SID). You can still have a column for your computed value, that can be set unique accross the table => you will keep the desired functionnality. But you will have much more efficient searches and joins on this table with an int primary key.
And to answer to your question, here is the version for SQL Compact:
create table Student ( SID int PRIMARY KEY IDENTITY(1,1), STID nvarchar(14)) UNIQUE NOT NULL, Name nvarchar(20) NOT NULL, City nvarchar(30) NOT NULL, Phone varchar(10) NOT NULL );
But, as it has been told to you, with SQL Server Compact you will have to handle the creation of the STID value in your code, as the database engine cannot handle that for you. Something like:
Student.STID = string.Format("SID-{0}", student.SID);
Hope this helps.
这篇关于在字符和数字之间建立主键混合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!