Showing posts with label key. Show all posts
Showing posts with label key. Show all posts

Sunday, March 25, 2012

Backing up Encryption Master Key

Hello,
I have problems backing up the Master key. The message is cannot write into
file 'file path' verify that you have the write permissions. I don't
understand why because I am using user dbo and defaul schema dbo on the
database.
If someone can help me to clarify the permissions part.
Thanks for your help.Make sure the SQL Server service account has write access to the path where
you want to save the file.
Thanks
Laurentiu Cristofor [MSFT]
Software Development Engineer
SQL Server Engine
http://blogs.msdn.com/lcris/
This posting is provided "AS IS" with no warranties, and confers no rights.
"Car" <Car@.discussions.microsoft.com> wrote in message
news:AF3C125B-D6D3-4304-87F2-C332DD562626@.microsoft.com...
> Hello,
> I have problems backing up the Master key. The message is cannot write
> into
> file 'file path' verify that you have the write permissions. I don't
> understand why because I am using user dbo and defaul schema dbo on the
> database.
> If someone can help me to clarify the permissions part.
> Thanks for your help.|||Well I am not login as sa. I am using windows authentication and the login
user I have is member of the Administrators group on the local computer wher
e
I am trying to save the file containing the backup of the master key.
Thanks for your help anyway.
"Laurentiu Cristofor [MSFT]" wrote:

> Make sure the SQL Server service account has write access to the path wher
e
> you want to save the file.
> Thanks
> --
> Laurentiu Cristofor [MSFT]
> Software Development Engineer
> SQL Server Engine
> http://blogs.msdn.com/lcris/
> This posting is provided "AS IS" with no warranties, and confers no rights
.
> "Car" <Car@.discussions.microsoft.com> wrote in message
> news:AF3C125B-D6D3-4304-87F2-C332DD562626@.microsoft.com...
>
>|||How you connect and the permissions you have don't matter in this case -
when you go outside the server, you go out with the service account
credentials, not with the credentials you connected to the server.
So, find out what account SQL Server is running as, and make sure that
account has access to the location where you want to save the backup file.
Thanks
Laurentiu Cristofor [MSFT]
Software Development Engineer
SQL Server Engine
http://blogs.msdn.com/lcris/
This posting is provided "AS IS" with no warranties, and confers no rights.
"Car" <Car@.discussions.microsoft.com> wrote in message
news:DFF1B05E-DE27-4C72-BCE5-16C640CDFCB3@.microsoft.com...[vbcol=seagreen]
> Well I am not login as sa. I am using windows authentication and the
> login
> user I have is member of the Administrators group on the local computer
> where
> I am trying to save the file containing the backup of the master key.
>
> Thanks for your help anyway.
> "Laurentiu Cristofor [MSFT]" wrote:
>|||I got it. I find out that the SQL Server Account I was running does not hav
e
permissions on the Local computer. Now I am running the backup statements a
s
a job under the right account and I have to create another job to restore th
e
backup of the master key into the suscriber database.
Thanks again for your assistance.
"Laurentiu Cristofor [MSFT]" wrote:

> How you connect and the permissions you have don't matter in this case -
> when you go outside the server, you go out with the service account
> credentials, not with the credentials you connected to the server.
> So, find out what account SQL Server is running as, and make sure that
> account has access to the location where you want to save the backup file.
> Thanks
> --
> Laurentiu Cristofor [MSFT]
> Software Development Engineer
> SQL Server Engine
> http://blogs.msdn.com/lcris/
> This posting is provided "AS IS" with no warranties, and confers no rights
.
> "Car" <Car@.discussions.microsoft.com> wrote in message
> news:DFF1B05E-DE27-4C72-BCE5-16C640CDFCB3@.microsoft.com...
>
>sql

Saturday, February 25, 2012

AWE /3GB performance

Is it possible to use AWE and /3gb option and cause the OS to become
constrained? Is so what key OS services are critical and which ones should
be stopped?
thank
-JohnJohn
If you have Windows 2000(Advanced or Datacenter) and 4GB RAM use /3GB (AWE
support isn't used)
You can provide more info to get more accurate advice
"John Grant" <JohnGrant@.discussions.microsoft.com> wrote in message
news:617A3083-DBEA-46C4-AFBE-C501839D12C7@.microsoft.com...
> Is it possible to use AWE and /3gb option and cause the OS to become
> constrained? Is so what key OS services are critical and which ones
> should
> be stopped?
> thank
> -John|||Hello John,
You can also use \PAE option if memory is more on the server e.g.8 GB and
SQL Server 2005 will manage the memory dynamically after the enabling the
AWE option.
Good Luck!
MB
"John Grant" <JohnGrant@.discussions.microsoft.com> wrote in message
news:617A3083-DBEA-46C4-AFBE-C501839D12C7@.microsoft.com...
> Is it possible to use AWE and /3gb option and cause the OS to become
> constrained? Is so what key OS services are critical and which ones
> should
> be stopped?
> thank
> -John|||John
>The /3GB switch is used to tell SQL Server to take advantage of 3GB out of
>the base 4GB of RAM that Windows 2000/3 supports natively. If you don't
>specify >this option, then SQL Server will only take advantage of 2GB of
>the first 4GB of RAM in the server, essentially wasting 1GB of RAM.
http://www.sql-server-performance.com/awe_memory.asp
"John Grant" <JohnGrant@.discussions.microsoft.com> wrote in message
news:A6CF4DB6-FFEE-4AA0-82B8-DD3BB04E6D74@.microsoft.com...
>I have 8gb of memory, win2003 server advanced, sql server 2000 ent. The
> concern when using the 3gb option is that I force the OS into 1gb of
> memory
> and causing the OS to be memory starved. Is it possible to create this
> condition and what would be the minimum set of services that should be
> running on the SQL Server box. For example, print spooler, application
> layer
> gateway, etc.
>
> "Uri Dimant" wrote:
>> John
>> If you have Windows 2000(Advanced or Datacenter) and 4GB RAM use /3GB
>> (AWE
>> support isn't used)
>> You can provide more info to get more accurate advice
>> "John Grant" <JohnGrant@.discussions.microsoft.com> wrote in message
>> news:617A3083-DBEA-46C4-AFBE-C501839D12C7@.microsoft.com...
>> > Is it possible to use AWE and /3gb option and cause the OS to become
>> > constrained? Is so what key OS services are critical and which ones
>> > should
>> > be stopped?
>> >
>> > thank
>> > -John
>>|||John
Is it SQL Server running dedicated on the server?
Do you have an OLTP applications connect to the SQL Server?
I'd strat to to identify perfomance problems from the application side (
checking indexes, database design)
"John Grant" <JohnGrant@.discussions.microsoft.com> wrote in message
news:DD6405A3-56C5-4394-81D5-121D204420F3@.microsoft.com...
> Uri, thanks for the info. I have read the doc and understand AWE and the
> 3gb
> option. Also I noticed some more advanced boot.ini options to control the
> use of the memory above 1g.
> I have a sql server that is running slow. I have not been able to profile
> the server. What I want to understand is "Is it possible to cause the OS
> to
> be memory starved using the 3gb option causing sql server to appear slow?"
> For example if the OS is forced to swap to disk for normal OS activities.
> If it is possible what would be the telling signs?
> thanks
> "Uri Dimant" wrote:
>> John
>> >The /3GB switch is used to tell SQL Server to take advantage of 3GB out
>> >of
>> >the base 4GB of RAM that Windows 2000/3 supports natively. If you don't
>> >specify >this option, then SQL Server will only take advantage of 2GB of
>> >the first 4GB of RAM in the server, essentially wasting 1GB of RAM.
>> http://www.sql-server-performance.com/awe_memory.asp
>>
>>
>> "John Grant" <JohnGrant@.discussions.microsoft.com> wrote in message
>> news:A6CF4DB6-FFEE-4AA0-82B8-DD3BB04E6D74@.microsoft.com...
>> >I have 8gb of memory, win2003 server advanced, sql server 2000 ent. The
>> > concern when using the 3gb option is that I force the OS into 1gb of
>> > memory
>> > and causing the OS to be memory starved. Is it possible to create this
>> > condition and what would be the minimum set of services that should be
>> > running on the SQL Server box. For example, print spooler, application
>> > layer
>> > gateway, etc.
>> >
>> >
>> > "Uri Dimant" wrote:
>> >
>> >> John
>> >>
>> >> If you have Windows 2000(Advanced or Datacenter) and 4GB RAM use
>> >> /3GB
>> >> (AWE
>> >> support isn't used)
>> >> You can provide more info to get more accurate advice
>> >>
>> >> "John Grant" <JohnGrant@.discussions.microsoft.com> wrote in message
>> >> news:617A3083-DBEA-46C4-AFBE-C501839D12C7@.microsoft.com...
>> >> > Is it possible to use AWE and /3gb option and cause the OS to become
>> >> > constrained? Is so what key OS services are critical and which ones
>> >> > should
>> >> > be stopped?
>> >> >
>> >> > thank
>> >> > -John
>> >>
>> >>
>> >>
>>

Friday, February 24, 2012

Avoiding "Violation of Primary Key" with replication

I have a centralized database (server A), and two remote databases
(server B & C) all with a copy of the same database with a table with
user entered, primary key like ProductID. There is a possiblity that
the same ProductID gets entered into both B & C (which is ok).
I create a snapshot of B and replicate to A.
Is there a way to replicate C to server A and have replication ignore
any Primary Key violations during replication?
you can select the continue on data consistency profile. To do this right
click on your distribution agent and select agent profiles.
I would however advise you to come up with some partitioning scheme -
whether this involves adding another column to your pk with a location
specific parameter, or if you are using the identity property on you pk, go
to server b and type
DBCC Checkident ('YourTable',1000000)
Hilary Cotter
Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602.html
Looking for a FAQ on Indexing Services/SQL FTS
http://www.indexserverfaq.com
<dkolva@.atlab.com> wrote in message
news:1110815869.167577.303520@.g14g2000cwa.googlegr oups.com...
> I have a centralized database (server A), and two remote databases
> (server B & C) all with a copy of the same database with a table with
> user entered, primary key like ProductID. There is a possiblity that
> the same ProductID gets entered into both B & C (which is ok).
> I create a snapshot of B and replicate to A.
> Is there a way to replicate C to server A and have replication ignore
> any Primary Key violations during replication?
>

Avoid Inserting Duplicate Entries

Hi all,

I am somewhat new to sql server. So help me in whatever way you can.

I have two tables one of which doesnt have a primary key(table A) and other has a composite key formed of two columns(table B). I need to insert entries in table B from table A(table A has a unique constratint UID which is passed to table B). Table B also has a unique ID which is different from UID of table A.

Sometimes table A tries to insert a duplicate entry which is denied by table B since it has a primary key.

The insert query is as below.

table A - CORE
table B - CRF

INSERT INTO CRF (CORE_UID,ACCT_NUM_MIN, ACCT_NUM_MAX,BIN, BUS_ID,BUS_NM,ISO_CTRY_CD, REGN_CD, PROD_TYPE_CD, CARD_TYPE)
(SELECT UID,LEFT(ACCT_NUM_MIN,16),LEFT( ACCT_NUM_MAX,16),BIN, BUS_ID,BUS_NM,ISO_CTRY_CD, REGN_CD, PROD_TYPE_CD, CARD_TYPE FROM CORE WHERE UID NOT IN (SELECT CORE_UID FROM CRF))

I am not worried about the performance. I have tried if not exists and except but since i am new i am not able to figure out the problem.

Thank you in advance for all who try to help me out.

Quote:

Originally Posted by desirocks

Hi all,

I am somewhat new to sql server. So help me in whatever way you can.

I have two tables one of which doesnt have a primary key(table A) and other has a composite key formed of two columns(table B). I need to insert entries in table B from table A(table A has a unique constratint UID which is passed to table B). Table B also has a unique ID which is different from UID of table A.

Sometimes table A tries to insert a duplicate entry which is denied by table B since it has a primary key.

The insert query is as below.

table A - CORE
table B - CRF

INSERT INTO CRF (CORE_UID,ACCT_NUM_MIN, ACCT_NUM_MAX,BIN, BUS_ID,BUS_NM,ISO_CTRY_CD, REGN_CD, PROD_TYPE_CD, CARD_TYPE)
(SELECT UID,LEFT(ACCT_NUM_MIN,16),LEFT( ACCT_NUM_MAX,16),BIN, BUS_ID,BUS_NM,ISO_CTRY_CD, REGN_CD, PROD_TYPE_CD, CARD_TYPE FROM CORE WHERE UID NOT IN (SELECT CORE_UID FROM CRF))

I am not worried about the performance. I have tried if not exists and except but since i am new i am not able to figure out the problem.

Thank you in advance for all who try to help me out.


i believe CONSTRAINT are still the best way to enforce your data integrity. you can also do this through trigger or check the table before insert, but i believe it'll be slower.|||

Quote:

Originally Posted by ck9663

i believe CONSTRAINT are still the best way to enforce your data integrity. you can also do this through trigger or check the table before insert, but i believe it'll be slower.


I AM NOT CONCERNED WITH THE PERFORMANCE... CAN YOU HELP ME WRITE THIS TRIGGER OR PROVIDE SYNTAX TO CHECK THE TABLE BEFORE THE INSERT?|||

Quote:

Originally Posted by desirocks

Hi all,

I am somewhat new to sql server. So help me in whatever way you can.

I have two tables one of which doesnt have a primary key(table A) and other has a composite key formed of two columns(table B). I need to insert entries in table B from table A(table A has a unique constratint UID which is passed to table B). Table B also has a unique ID which is different from UID of table A.

Sometimes table A tries to insert a duplicate entry which is denied by table B since it has a primary key.

The insert query is as below.

table A - CORE
table B - CRF

INSERT INTO CRF (CORE_UID,ACCT_NUM_MIN, ACCT_NUM_MAX,BIN, BUS_ID,BUS_NM,ISO_CTRY_CD, REGN_CD, PROD_TYPE_CD, CARD_TYPE)
(SELECT UID,LEFT(ACCT_NUM_MIN,16),LEFT( ACCT_NUM_MAX,16),BIN, BUS_ID,BUS_NM,ISO_CTRY_CD, REGN_CD, PROD_TYPE_CD, CARD_TYPE FROM CORE WHERE UID NOT IN (SELECT CORE_UID FROM CRF))

I am not worried about the performance. I have tried if not exists and except but since i am new i am not able to figure out the problem.

Thank you in advance for all who try to help me out.


Your above INSERT QUERY should work fine. What is the problem that you are facing here??|||

Quote:

Originally Posted by amitpatel66

Your above INSERT QUERY should work fine. What is the problem that you are facing here??


Since table CRF does have a composite key it doesnt allow duplicate entries and hence my application gives me an error. I want to some how check if the entry already exists or not and based upon the same i need to insert. Is there some way i can change the query ?|||It would help to know what column(s) comprise your primary key on table B. You say that A nad B have different unique columns, but your insert statement only limits duplicates based on table A's unique key. If table B has a different unique key then that is what you need to check fo in your not in statement. Also, a NOT EXISTS should be faster, but first you need to figure out what is unique on table B.|||OK, since you have said B has a composite key then you need something like this (I assumed that CORE_UID, BIN was the composite key, so adjust as needed):
INSERT INTO CRF (CORE_UID,
ACCT_NUM_MIN,
ACCT_NUM_MAX,
BIN,
BUS_ID,
BUS_NM,
ISO_CTRY_CD,
REGN_CD,
PROD_TYPE_CD,
CARD_TYPE)
SELECT UID,
LEFT(ACCT_NUM_MIN,16),
LEFT(ACCT_NUM_MAX,16),
BIN,
BUS_ID,
BUS_NM,
ISO_CTRY_CD,
REGN_CD,
PROD_TYPE_CD,
CARD_TYPE
FROM CORE A
WHERE NOT EXISTS (SELECT 1 FROM CRF B WHERE B.CORE_UID = A.UID and B.BIN = A.BIN)|||

Quote:

Originally Posted by rob313

OK, since you have said B has a composite key then you need something like this (I assumed that CORE_UID, BIN was the composite key, so adjust as needed):
INSERT INTO CRF (CORE_UID,
ACCT_NUM_MIN,
ACCT_NUM_MAX,
BIN,
BUS_ID,
BUS_NM,
ISO_CTRY_CD,
REGN_CD,
PROD_TYPE_CD,
CARD_TYPE)
SELECT UID,
LEFT(ACCT_NUM_MIN,16),
LEFT(ACCT_NUM_MAX,16),
BIN,
BUS_ID,
BUS_NM,
ISO_CTRY_CD,
REGN_CD,
PROD_TYPE_CD,
CARD_TYPE
FROM CORE A
WHERE NOT EXISTS (SELECT 1 FROM CRF B WHERE B.CORE_UID = A.UID and B.BIN = A.BIN)


hi rob,

The composite key comprises of ACCT_NUM_MIN and ACCT_NUM_MAX. The UID of CORE is being transferred to CRF and CRF also has its own UID. Can you specify what whould be the change in the query now?|||In that case, this should work:

INSERT INTO CRF (CORE_UID,
ACCT_NUM_MIN,
ACCT_NUM_MAX,
BIN,
BUS_ID,
BUS_NM,
ISO_CTRY_CD,
REGN_CD,
PROD_TYPE_CD,
CARD_TYPE)
SELECT UID,
LEFT(ACCT_NUM_MIN,16),
LEFT(ACCT_NUM_MAX,16),
BIN,
BUS_ID,
BUS_NM,
ISO_CTRY_CD,
REGN_CD,
PROD_TYPE_CD,
CARD_TYPE
FROM CORE A
WHERE NOT EXISTS (SELECT 1 FROM CRF B WHERE B.ACCT_NUM_MIN = A.LEFT(ACCT_NUM_MIN,16) and B.ACCT_NUM_MAX = A.LEFT(ACCT_NUM_MAX,16))

Avoid duplicate primary key error

How can I avoid duplicate primary key error when I use DetailsView Inserting that the field column is one of the primary key ?

Thanks in advance !

stephen

Before insertin the new row, you can check the table to see whether there is a row in the table with the same key value as the new row. For example:

if exists (select * from Orders where OrderID=@.newOrderID)

//not insert

else //insert

|||

Can you show me the detail of correct syntax ? I'm very new in ASP.NET 2.0. I did type the statement in the ??.aspx.cs and syntax error found.

stephen

|||

Sorry I forgot to say: the code in my last post is T-SQL statements, so you can use them in SqlCommand or something else.

Sunday, February 19, 2012

Avoid Cross Database Views in Data Warehouse

We have a relational database (rd) and a data warehouse (dw). This dw has a table (tw) with all key fields (dimension keys) and metric related (measures) fields. This table is populated with monthly data each month. The tw is joined to various look up views present in the dw to obtain name fields from rd. The DBA wants me to remove the look up views. I now have following 2 options that I can think of –

1) Further de-normalize the tw and store the name fields as well. However, there are two issues with this option –

a. The size of tw will grow tremendously.
b. We are storing monthly data and the values in the name fields may change after some time. Then we will have to put in additional views/objects to obtain the latest name.

2) Using ETL, obtain the copy of rd tables overnight in dw. We will then join tw with these tables and there will no longer be cross database joins. However, this will be a burden on maintenance and support.

As of now these are the possible options I can come up with. Which one would you suggest and why? If you have another option, please let me know.

Thank you all in advance,

sajmeraWe have a relational database (rd) and a data warehouse (dw).
No you don't. You have a datamart. If you had a real data warehouse schema you would not have these issues.

The DBA wants me to remove the look up views.
Why?

2) Using ETL, obtain the copy of rd tables overnight in dw. We will then join tw with these tables and there will no longer be cross database joins. However, this will be a burden on maintenance and support.
A data warehouse (or datamart) should be self-contained, and not rely upon pulling dynamic data from other systems. Maintenance and support are necessary requirements of a data stores.

Friday, February 10, 2012

AutoNumber with specified format

Hi all,
In SQLServer 2005, are there any method to create the autonumber with
specific format?
for example,
I would like to have a key which the pattern is ABC00001 and the next
autonumber is ABC00002 and the next autonumber is ABC00003...
However, I won't like to handle it in the front-end application. Any idea?
Regards
alexGood wrote:
> Hi all,
> In SQLServer 2005, are there any method to create the autonumber with
> specific format?
> for example,
> I would like to have a key which the pattern is ABC00001 and the next
> autonumber is ABC00002 and the next autonumber is ABC00003...
> However, I won't like to handle it in the front-end application. Any
> idea?
> Regards
> alex
You'll have to roll that solution yourself. Your proposed key will
consume 8 bytes and give you only 100,000 values - unless you change the
prefix. In any case, I would store the next value as a numeric in a
"next key table" and use an instead of insert trigger on the table to
automatically create the key values. For example:
Set nocount on
go
create table dbo.NextKey (TableName nvarchar(255) not null primary key,
NextKeyVal int not null default 1)
insert into dbo.NextKey (TableName) Values ('TestTable')
Select * from dbo.NextKey
go
Create Table dbo.TestTable (SomeID char(8) not null primary key, SomeCol
int not null)
go
Drop Trigger TestTableIOI
go
Create Trigger TestTableIOI on dbo.TestTable Instead Of Insert
as
Begin
Declare @.NextKeyVal int
If (Select count(*) from inserted) != 1
RAISERROR ('Only one row inserted at a time please', 15, 1)
Else Begin
Update dbo.NextKey Set @.NextKeyVal = NextKeyVal = NextKeyVal + 1
Where TableName = N'TestTable'
If @.NextKeyVal Is Null
RAISERROR ('Could not determine next key value for table: %s', 15,
1, N'TestTable')
Else Begin
Insert dbo.TestTable (SomeID, SomeCol)
Select 'ABC' + right('00000' + cast(@.NextKeyVal as varchar(5)),
5), SomeCol From inserted
End
End
End
Go
Insert into dbo.TestTable (SomeID, SomeCol) Values ('', 5) -- Note: Must
supply a dummy value for PK
Insert into dbo.TestTable (SomeID, SomeCol) Values ('', 5) -- Note: Must
supply a dummy value for PK
Insert into dbo.TestTable (SomeID, SomeCol) Values ('', 5) -- Note: Must
supply a dummy value for PK
Insert into dbo.TestTable (SomeID, SomeCol) Values ('', 5) -- Note: Must
supply a dummy value for PK
Insert into dbo.TestTable (SomeID, SomeCol) Values ('', 5) -- Note: Must
supply a dummy value for PK
Select * from dbo.TestTable
Go
Drop Table dbo.TestTable
Drop Table dbo.NextKey
David Gugick - SQL Server MVP
Quest Software|||Alternatively, go with the identity column and use a computed column to gene
rate
the value derived from the identity column. In your example it looks like
the identity you need is just a concatenation of the identity value with
a fixed prefix. For example,
create function dbo.IdAsMyId (@.id int)
returns char(8)
as begin
declare @.prefix char(3);
set @.prefix = 'ABC';
declare @.leadingZeros int;
set @.leadingZeros = 8 - len(@.id) - len(@.prefix);
declare @.myId char(8)
set @.myId = 'ABC' + replicate('0', @.leadingZeros) + cast(@.id as varchar(5));
return @.myId;
end
go
create table CustomIdentity (
id int identity(1,1),
myId as dbo.IdAsMyId(id),
data varchar(255))
go
insert CustomIdentity (data) values ('One')
insert CustomIdentity (data) values ('Two')
insert CustomIdentity (data) values ('Three')
go
select *
from CustomIdentity
go
You probaby want to index the computed column if you're going to search on
it.
Cheers,
Stefan
http://www.fotia.co.uk

> Good wrote:
>
> You'll have to roll that solution yourself. Your proposed key will
> consume 8 bytes and give you only 100,000 values - unless you change
> the prefix. In any case, I would store the next value as a numeric in
> a "next key table" and use an instead of insert trigger on the table
> to automatically create the key values. For example:
> Set nocount on
> go
> create table dbo.NextKey (TableName nvarchar(255) not null primary
> key,
> NextKeyVal int not null default 1)
> insert into dbo.NextKey (TableName) Values ('TestTable')
> Select * from dbo.NextKey
> go
> Create Table dbo.TestTable (SomeID char(8) not null primary key,
> SomeCol
> int not null)
> go
> Drop Trigger TestTableIOI
> go
> Create Trigger TestTableIOI on dbo.TestTable Instead Of Insert
> as
> Begin
> Declare @.NextKeyVal int
> If (Select count(*) from inserted) != 1
> RAISERROR ('Only one row inserted at a time please', 15, 1)
> Else Begin
> Update dbo.NextKey Set @.NextKeyVal = NextKeyVal = NextKeyVal + 1
> Where TableName = N'TestTable'
> If @.NextKeyVal Is Null
> RAISERROR ('Could not determine next key value for table: %s',
> 15,
> 1, N'TestTable')
> Else Begin
> Insert dbo.TestTable (SomeID, SomeCol)
> Select 'ABC' + right('00000' + cast(@.NextKeyVal as varchar(5)),
> 5), SomeCol From inserted
> End
> End
> End
> Go
> Insert into dbo.TestTable (SomeID, SomeCol) Values ('', 5) -- Note:
> Must
> supply a dummy value for PK
> Insert into dbo.TestTable (SomeID, SomeCol) Values ('', 5) -- Note:
> Must
> supply a dummy value for PK
> Insert into dbo.TestTable (SomeID, SomeCol) Values ('', 5) -- Note:
> Must
> supply a dummy value for PK
> Insert into dbo.TestTable (SomeID, SomeCol) Values ('', 5) -- Note:
> Must
> supply a dummy value for PK
> Insert into dbo.TestTable (SomeID, SomeCol) Values ('', 5) -- Note:
> Must
> supply a dummy value for PK
> Select * from dbo.TestTable
> Go
> Drop Table dbo.TestTable
> Drop Table dbo.NextKey|||Stefan Delmarco wrote:
> Alternatively, go with the identity column and use a computed column
> to generate the value derived from the identity column. In your
> example it looks like the identity you need is just a concatenation of
> the identity value
> with a fixed prefix. For example,
>
I think if you go that route you are better off using a computed column
without the scalar function.
create table TestTable (id int identity not null primary key, ak as
'ABC' + right('00000' + cast(id as varchar(5)), 5), col1 int not null)
create unique index TestTable_ak on TestTable (ak)
go
insert into TestTable (col1) values (1)
insert into TestTable (col1) values (2)
insert into TestTable (col1) values (3)
Select * from TestTable
go
drop table TestTable
David Gugick - SQL Server MVP
Quest Software

AutoNumber vs. Key

Hi,

I am always confused about what to use as the key for a table.

Let's say I have a company-employee table.

[company]--*[employee]

My co-worker likes to use an AutoNumber or Counter as the key for the
[employee] table (and everything).
I personally use an actual key set for the [employee] table.

So, his table will have one (Autonumber or LONG) column as the key. The
company_id is just another attribute.
Mine, on the other hand, has 2 columns as the key. (i.e.) company_id +
employee_id

So, what is the deal?

--
> There is no answer.
> There has not been an answer.
> There will not be an answer.
> That IS the answer!
> And I am screwed.
> Deadline was due yesterday.
> There is no point to life.
> THAT IS THE POINT.
> And we are screwed.
> We will run out of oil soon.always use an autonumber identity for everythign you do

single-column primary key|||"For everything" is a pretty obscure answer. Other keys are important
too. In a joining table containing only two foreign keys for example
what purpose would IDENTITY serve?

Tom, for the debate you can Google for "Natural Key" and "Surrogate
Key" in this group and in microsoft.public.sqlserver.programming.

--
David Portas
SQL Server MVP
--|||Hi,

Is there a reason for using one and only one column as the key?
I find it hard to enforce the integrity of the database with this design.

for example,
let's say the [company]-[employee]-[sale] tables.
company A has an employee B.
employee B makes a sale C.

If employee B moves to another company, the sale C in the [sale] table will
move along with employee B to the new company.
This doesn't look correct to me.

<dbahooker@.hotmail.com> wrote in message
news:1129059631.679988.51060@.g47g2000cwa.googlegro ups.com...
> always use an autonumber identity for everythign you do
> single-column primary key|||Thanks for the actual terms for these key thingies.

I've searched google but found a lot of different opinions.
Some like autonumber but some like... huh... natural key.

To sum it up from all the posts I've read:
1)
The people who use autonumber said that it performed better and easier to
update the record without affecting the database integrity. (imagine
someone needs to change his or her social security number!!!! all hell broke
lose!!!)

2)
The people who use natural key said that people who use surrogate were just
lazy and not experience with database design. And using natural key could
better model database to the business model.

So... I don't know... that's why I am so confused.
One has physical advantage. The other has logical advantage.

"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:1129060967.267313.134080@.z14g2000cwz.googlegr oups.com...
> "For everything" is a pretty obscure answer. Other keys are important
> too. In a joining table containing only two foreign keys for example
> what purpose would IDENTITY serve?
> Tom, for the debate you can Google for "Natural Key" and "Surrogate
> Key" in this group and in microsoft.public.sqlserver.programming.
> --
> David Portas
> SQL Server MVP
> --|||Tom (nospam@.yahoo.com) writes:
> I am always confused about what to use as the key for a table.
> Let's say I have a company-employee table.
> [company]--*[employee]
> My co-worker likes to use an AutoNumber or Counter as the key for the
> [employee] table (and everything).
> I personally use an actual key set for the [employee] table.
> So, his table will have one (Autonumber or LONG) column as the key. The
> company_id is just another attribute.
> Mine, on the other hand, has 2 columns as the key. (i.e.) company_id +
> employee_id

I would say that the two alternatives describes two different things.
In the one-column case, an employee is rather a person, and if he
moves to another company all data that is tied to him are brought with
him.

In the two-column case, you get a new row when he gets a new job.

The latter appears more useful to me. If we want to know who much sales
did everyone in company X generate last year, we can't tell with the
first setup, since we don't know who worked where that year.

If want to know how much aales Bob has generated over the years in
different company, maybe there should be a person table, to which
employees have a reference.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||I come to the same conclusion. (see the 10/11/2005 1:03pm post)

As I search Google, this thing is getting very confusing. All the posts
point to the one dead end conclusion -- "It depends".

I need something solid so I don't have to reinvent the wheel (or think about
it). The "It depends" thing just doesn't cut it.

"Erland Sommarskog" <esquel@.sommarskog.se> wrote in message
news:Xns96ECF3C9E8AE7Yazorman@.127.0.0.1...
> Tom (nospam@.yahoo.com) writes:
>> I am always confused about what to use as the key for a table.
>>
>> Let's say I have a company-employee table.
>>
>> [company]--*[employee]
>>
>> My co-worker likes to use an AutoNumber or Counter as the key for the
>> [employee] table (and everything).
>> I personally use an actual key set for the [employee] table.
>>
>> So, his table will have one (Autonumber or LONG) column as the key. The
>> company_id is just another attribute.
>> Mine, on the other hand, has 2 columns as the key. (i.e.) company_id +
>> employee_id
> I would say that the two alternatives describes two different things.
> In the one-column case, an employee is rather a person, and if he
> moves to another company all data that is tied to him are brought with
> him.
> In the two-column case, you get a new row when he gets a new job.
> The latter appears more useful to me. If we want to know who much sales
> did everyone in company X generate last year, we can't tell with the
> first setup, since we don't know who worked where that year.
> If want to know how much aales Bob has generated over the years in
> different company, maybe there should be a person table, to which
> employees have a reference.
>
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server SP3 at
> http://www.microsoft.com/sql/techin.../2000/books.asp|||"Tom" <nospam@.yahoo.com> wrote in message
news:hiY2f.481$7h7.465@.newssvr21.news.prodigy.com. ..
> I come to the same conclusion. (see the 10/11/2005 1:03pm post)
> As I search Google, this thing is getting very confusing. All the posts
> point to the one dead end conclusion -- "It depends".
> I need something solid so I don't have to reinvent the wheel (or think
about
> it). The "It depends" thing just doesn't cut it.

"It depends" .

Basically I tend to agree with Celko's philosophy that wheer possible the
key should model reality. If your employees already have some sort of
employee number assigned, use that.

That said, even in many of my tables with natural keys I'll drop in an
Identity column as it can be useful for some ad-hoc queries.

>
> "Erland Sommarskog" <esquel@.sommarskog.se> wrote in message
> news:Xns96ECF3C9E8AE7Yazorman@.127.0.0.1...
> > Tom (nospam@.yahoo.com) writes:
> >> I am always confused about what to use as the key for a table.
> >>
> >> Let's say I have a company-employee table.
> >>
> >> [company]--*[employee]
> >>
> >> My co-worker likes to use an AutoNumber or Counter as the key for the
> >> [employee] table (and everything).
> >> I personally use an actual key set for the [employee] table.
> >>
> >> So, his table will have one (Autonumber or LONG) column as the key.
The
> >> company_id is just another attribute.
> >> Mine, on the other hand, has 2 columns as the key. (i.e.) company_id +
> >> employee_id
> > I would say that the two alternatives describes two different things.
> > In the one-column case, an employee is rather a person, and if he
> > moves to another company all data that is tied to him are brought with
> > him.
> > In the two-column case, you get a new row when he gets a new job.
> > The latter appears more useful to me. If we want to know who much sales
> > did everyone in company X generate last year, we can't tell with the
> > first setup, since we don't know who worked where that year.
> > If want to know how much aales Bob has generated over the years in
> > different company, maybe there should be a person table, to which
> > employees have a reference.
> > --
> > Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> > Books Online for SQL Server SP3 at
> > http://www.microsoft.com/sql/techin.../2000/books.asp|||Just my .02:

If you have a natural key that is VERY constant (more constant than a
name, because names can change) and is simple, use it. If you don't,
use a surrogate key, but be sure that your application and database can
handle data verification (avoiding duplicate records, etc).

Stu|||Tom (nospam@.yahoo.com) writes:
> I come to the same conclusion. (see the 10/11/2005 1:03pm post)
> As I search Google, this thing is getting very confusing. All the posts
> point to the one dead end conclusion -- "It depends".

Yes, that is a very common answer in the database world. And that does
not only apply to data modelling, but also how you should apply indexes,
write queries, implement backup strategies, you name it. It all matters
very much on the actual situations, and which trade-offs you want to make.

So in the end, it boils down do common sense and gut feeling for the
actual case at hand. What is bad is to follow a checklist that says
"Always do X".

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||On Tue, 11 Oct 2005 20:44:08 GMT, "Tom" <nospam@.yahoo.com> wrote:

>Thanks for the actual terms for these key thingies.
>I've searched google but found a lot of different opinions.
>Some like autonumber but some like... huh... natural key.
>To sum it up from all the posts I've read:
>1)
>The people who use autonumber said that it performed better and easier to
>update the record without affecting the database integrity. (imagine
>someone needs to change his or her social security number!!!! all hell broke
>lose!!!)
>2)
>The people who use natural key said that people who use surrogate were just
>lazy and not experience with database design. And using natural key could
>better model database to the business model.
>So... I don't know... that's why I am so confused.
>One has physical advantage. The other has logical advantage.

Unfortunately, all any of us can do is add more opinions to the pile, which is
not likely to generate any final closure, just give you more to ponder. I'll
try to offer what I think is useful, though.

- A table may have one key or more than one "key". It's not so much a
quesiton of whether a table should have a logical or surrogate key as whether
it should have a surrogate key in addition to one or more logical keys, and
use the surrogate key for joins.

- When multiple levels of 1-to-many relationship exist, surrogate keys can
prevent adding additional key fields at each level and coupling fine levels of
detail too closely to the models at courser levels.

- When a table has a surrogate key that is always of the same type and
following the same naming convention, it's easier to generate reusable
client-side code that can do things like keep track of a record, requery it,
save updates after an off-line editing session, etc.

- Surrogate keys tend to be 32-bit numbers that are fairly small, and easy for
the database engine to process.

- Using cascading updates to handle logical key change propagation can result
in very expensive updates with wide-ranging run-time side effects.

- Using surrogate keys to identify record links across subsystems can lead to
excessively tight coupling and interdependency. If 2 subsystems should be
relatively autonomous, they should very likely -not- reference each other's
records by internal surrogate key. Instead, they might use the logical key,
or they might use some kind of globally unique identifier. They should also
be built to tolerate broken links.|||On Tue, 11 Oct 2005 20:03:49 GMT, "Tom" <nospam@.yahoo.com> wrote:

>Hi,
>Is there a reason for using one and only one column as the key?
>I find it hard to enforce the integrity of the database with this design.
>for example,
>let's say the [company]-[employee]-[sale] tables.
>company A has an employee B.
>employee B makes a sale C.
>If employee B moves to another company, the sale C in the [sale] table will
>move along with employee B to the new company.
>This doesn't look correct to me.

How does this problem relate to the use of logical vs surrogate keys? The
real, problem is that this model does not track what company the sale is made
for, and traversing the employee doesn't tell what company that is, it tells
what company the employee who made the sale -currently- works for. [sale]
needs its own direct link to [company] if that information needs to be
retrieved later.|||dbahooker@.hotmail.com wrote:
> always use an autonumber identity for everythign you do
> single-column primary key

And this advice is based on what computer science class taught where?
--
Daniel A. Morgan
http://www.psoug.org
damorgan@.x.washington.edu
(replace x with u to respond)|||Your whole mental model of RDBMS is wrong.

Exposed locators such as IDENTITY are not surrogate keys. A surrogate
is totally hidden from uers and maintained by the system -- think of
how an index works. If you change a natural key, the DRI actions will
cascade it for you. Hell does not break loose. But if your autonumber
and real key are out of synch,then you are screwed. Just enter the
same record several times to get different autonumbers on duplicate
rows. Drop all but one of the dups and then try to find all of the
referenced rows in other tables.

If you maintain the exposed locator by hand, you have extra work, extra
disk seeks and will eventually make a mistake, thus destroying your
data integrity. How would you validate and verify your data?

The UPC code just went from 10 to 13 digits. It does not matter if you
used an autonumber or the UPC, the UPC has to be updated. If you had
used a proper RDBMS design and SQL-92, you would do an ALTER DOMAIN and
a single update with CASCADE. This is one of the MANY reasons that
rows are not records. This is a problem in SQL Server because it is
still based on a contigous storage model, but other products are not,
so wind up using tools to write scripts.

Finally have you bothered to time the two approaches with small and
large tables? It does not make a difference until the table has to do
a lot of paging and redundant autonumbers accumulate. This is the
21-st century; we have 32 and 64 bit hardware, nano-second speeds,
multi-word instructions, parallel processing and really good disk
drives.|||Must be from somewhere in India where they program $QL $erver for Bill
Gates.

Mahahahaa!!! <G!
"DA Morgan" <damorgan@.psoug.org> wrote in message
news:1129217676.921233@.yasure...
> dbahooker@.hotmail.com wrote:
>> always use an autonumber identity for everythign you do
>>
>> single-column primary key
> And this advice is based on what computer science class taught where?
> --
> Daniel A. Morgan
> http://www.psoug.org
> damorgan@.x.washington.edu
> (replace x with u to respond)|||thanks for the tips.

But I need to follow the specs. The specs says that cascade update or
delete is not supported (along many other things like joinning tables is not
allowed). And it comes to a point that I have to say screw this. I am
going to use autonumber.

I am trying to look for any sounded and proven pattern. But searching
Google gives me only the "it depends" solution.

"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1129224960.345778.104210@.z14g2000cwz.googlegr oups.com...
> Your whole mental model of RDBMS is wrong.
> Exposed locators such as IDENTITY are not surrogate keys. A surrogate
> is totally hidden from uers and maintained by the system -- think of
> how an index works. If you change a natural key, the DRI actions will
> cascade it for you. Hell does not break loose. But if your autonumber
> and real key are out of synch,then you are screwed. Just enter the
> same record several times to get different autonumbers on duplicate
> rows. Drop all but one of the dups and then try to find all of the
> referenced rows in other tables.
> If you maintain the exposed locator by hand, you have extra work, extra
> disk seeks and will eventually make a mistake, thus destroying your
> data integrity. How would you validate and verify your data?
> The UPC code just went from 10 to 13 digits. It does not matter if you
> used an autonumber or the UPC, the UPC has to be updated. If you had
> used a proper RDBMS design and SQL-92, you would do an ALTER DOMAIN and
> a single update with CASCADE. This is one of the MANY reasons that
> rows are not records. This is a problem in SQL Server because it is
> still based on a contigous storage model, but other products are not,
> so wind up using tools to write scripts.
> Finally have you bothered to time the two approaches with small and
> large tables? It does not make a difference until the table has to do
> a lot of paging and redundant autonumbers accumulate. This is the
> 21-st century; we have 32 and 64 bit hardware, nano-second speeds,
> multi-word instructions, parallel processing and really good disk
> drives.|||> The specs says [...] joinning tables is not allowed [!!]

Quit now. Time spent on such a spec is time wasted.

--
David Portas
SQL Server MVP
--|||They do pay the bills though. ;)

"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:1129227183.899975.133870@.g47g2000cwa.googlegr oups.com...
>> The specs says [...] joinning tables is not allowed [!!]
> Quit now. Time spent on such a spec is time wasted.
> --
> David Portas
> SQL Server MVP
> --|||On 13 Oct 2005 10:36:00 -0700, --CELKO-- wrote:

>Your whole mental model of RDBMS is wrong.

Hi Joe,

You're whole mental model of surrogate keys is wrong.

>Exposed locators such as IDENTITY are not surrogate keys. A surrogate
>is totally hidden from uers and maintained by the system -- think of
>how an index works.

So don't display the surrogate key on the data entry screen.

>If you change a natural key, the DRI actions will
>cascade it for you. Hell does not break loose.

If you change a natural key in a table that has a surrogate key as well,
there's no need to cascade it, as there's no redundant storage of the
key values. Hell does not break losse AND you don't need to get locks on
half the tables in the database.

>But if your autonumber
>and real key are out of synch,then you are screwed.

Eh? How can they "get out of synch"? Please post proper DDL and DML to
clarify what you mean.

>Just enter the
>same record several times to get different autonumbers on duplicate
>rows. Drop all but one of the dups and then try to find all of the
>referenced rows in other tables.

That's not a result of IDENTITY, that's a result of forgetting to
include a CHECK constraint. Database theory 101.

>If you maintain the exposed locator by hand, you have extra work, extra
>disk seeks and will eventually make a mistake, thus destroying your
>data integrity.

That's the point - you DON'T maintain the surrogate key by hand.

>How would you validate and verify your data?

Same as you would do it: use the natural key.

>The UPC code just went from 10 to 13 digits. It does not matter if you
>used an autonumber or the UPC, the UPC has to be updated. If you had
>used a proper RDBMS design and SQL-92, you would do an ALTER DOMAIN and
>a single update with CASCADE.

For starters, SQL Server 2000 doesn't have a switch that customers can
just flick to get full SQL-92 compliance. There is no ALTER DOMAIN
command in SQL Server 2000.

Fortunately, those who had the foresight to add a surrogate key to the
Products table don't need ALTER DOMAIN, nor CASCADE. A simple ALTER
TABLE and a single UPDATE on one single table suffices.

>This is one of the MANY reasons that
>rows are not records. This is a problem in SQL Server because it is
>still based on a contigous storage model, but other products are not,
>so wind up using tools to write scripts.

You mean to imply that other RDBMS's have no autonumber facility? Get
off it. Less than one minute of googling gave me:

- SQL Server, DB2: IDENTITY (with some variations in syntax);
- MySQL, SQLite: AUTO_INCREMENT (with some variations in syntax);
- Postgres, Oracle, Sybase, Mimer: CREATE SEQUENCE (with some variations
in syntax).

http://sqlzoo.net/howto/source/z.dir/tip000001

>Finally have you bothered to time the two approaches with small and
>large tables?

The OP was not asking for an advice for a specific situation, but for a
generic truth on whether to use or avoid identity. Which of course there
isn't - since your religious insisting that IDENTITY should never be
used is just as fundamentally wrong as brainlessly whacking an IDENTITY
column onto each and every table.

In databases, "it depends" is the only reliable answer.

>It does not make a difference until the table has to do
>a lot of paging and redundant autonumbers accumulate.

Redundant autonumbers? Care to elaborate?

This is the
>21-st century; we have 32 and 64 bit hardware, nano-second speeds,
>multi-word instructions, parallel processing and really good disk
>drives.

But we also have applications that gather hundreds of rows per second,
and queries that run on million-row tables - situations that can't be
"tuned" by just throwing more and better hardware at it. Performance s
just as important a consideration as it ever was. And including or
removing a surrogate key can (in some situations) improve or damage
performance by several degrees of magnitude.

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||Tom wrote:
> thanks for the tips.
> But I need to follow the specs.

Not if the specification is valueless or harmful.

Part of what you are supposed to bring to the party is expert knowledge
with respect to relational database systems. You are supposed to
contribute ... not just follow orders.

Go back, with cogent reasoned arguments, and ask for changes.
--
Daniel A. Morgan
http://www.psoug.org
damorgan@.x.washington.edu
(replace x with u to respond)|||>> The specs says that cascade update or delete is not supported (along many other things like joinning tables is not allowed). <<

No joins means that you have a (realllly crappppy) file system and not
an RDBMS.

>> I am trying to look for any sounded and proven pattern. <<

The only proven patern I know in this situation based on 35+ yerts in
the trade is to update your resume and leave the sinking ship. Do it
fast so the stink of failure does not hang on your clothing.

..|||Tom wrote:
> Hi,
> Is there a reason for using one and only one column as the key?
> I find it hard to enforce the integrity of the database with this design.
> for example,
> let's say the [company]-[employee]-[sale] tables.
> company A has an employee B.
> employee B makes a sale C.
> If employee B moves to another company, the sale C in the [sale] table will
> move along with employee B to the new company.
> This doesn't look correct to me.

As a programmer, if you work for a company you already know that code
you write at such company belongs to the company, not to you. Why would
the sale in your example belong to the salesman and not the company in
the first place. The sale would be a sub record of the company, the
salesman is just an attribute.|||Hahahaha!!!
huh... <G!>
Well... they do pay the bill... and they do pay the bill ON TIME.
So... it is all good to me.
not to mention that I've already left my dignity in my house before I set
foot in my cubical.

"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1129252447.261815.6780@.z14g2000cwz.googlegrou ps.com...
>>> The specs says that cascade update or delete is not supported (along
>>> many other things like joinning tables is not allowed). <<
> No joins means that you have a (realllly crappppy) file system and not
> an RDBMS.
>>> I am trying to look for any sounded and proven pattern. <<
> The only proven patern I know in this situation based on 35+ yerts in
> the trade is to update your resume and leave the sinking ship. Do it
> fast so the stink of failure does not hang on your clothing.
> .

AutoNumber Primary Key

We are testing the upload of an Access 2002 data database to SQL Server
2000. Some of the tables had AutoNumber fields that were Random (due to it
being a replicated table in Access). The upload created triggers similar to
the example below. However, Access applications fail on insert because the
primary key field is not populated until the trigger runs. Any help is
appreciated.
CREATE TRIGGER T_AssessmentDocs_ITrig ON dbo.AssessmentDocs FOR INSERT AS
SET NOCOUNT ON
DECLARE @.randc int, @.newc int /* FOR AUTONUMBER-EMULATION CODE */
/* * RANDOM AUTONUMBER EMULATION CODE FOR FIELD 'DocID' */
SELECT @.randc = (SELECT convert(int, rand() * power(2, 30)))
SELECT @.newc = (SELECT DocID FROM inserted)
UPDATE AssessmentDocs SET DocID = @.randc WHERE DocID = @.newc
DavidDavid C wrote:
> We are testing the upload of an Access 2002 data database to SQL
> Server 2000. Some of the tables had AutoNumber fields that were
> Random (due to it being a replicated table in Access). The upload
> created triggers similar to the example below. However, Access
> applications fail on insert because the primary key field is not
> populated until the trigger runs. Any help is appreciated.
> CREATE TRIGGER T_AssessmentDocs_ITrig ON dbo.AssessmentDocs FOR
> INSERT AS SET NOCOUNT ON
> DECLARE @.randc int, @.newc int /* FOR AUTONUMBER-EMULATION CODE */
> /* * RANDOM AUTONUMBER EMULATION CODE FOR FIELD 'DocID' */
> SELECT @.randc = (SELECT convert(int, rand() * power(2, 30)))
> SELECT @.newc = (SELECT DocID FROM inserted)
> UPDATE AssessmentDocs SET DocID = @.randc WHERE DocID = @.newc
> David
Change the column to an IDENTITY value. SQL Server automates the
generation of the next value. You may have to seed the identity value
using the MAX(ID) + 1 in the table.
You can pull back the newly inserted identity value into the application
using the SCOPE_IDENTITY() function.
David Gugick
Imceda Software
www.imceda.com|||David Gugick wrote:
> David C wrote:
>> We are testing the upload of an Access 2002 data database to SQL
>> Server 2000. Some of the tables had AutoNumber fields that were
>> Random (due to it being a replicated table in Access). The upload
>> created triggers similar to the example below. However, Access
>> applications fail on insert because the primary key field is not
>> populated until the trigger runs. Any help is appreciated.
>> CREATE TRIGGER T_AssessmentDocs_ITrig ON dbo.AssessmentDocs FOR
>> INSERT AS SET NOCOUNT ON
>> DECLARE @.randc int, @.newc int /* FOR AUTONUMBER-EMULATION CODE */
>> /* * RANDOM AUTONUMBER EMULATION CODE FOR FIELD 'DocID' */
>> SELECT @.randc = (SELECT convert(int, rand() * power(2, 30)))
>> SELECT @.newc = (SELECT DocID FROM inserted)
>> UPDATE AssessmentDocs SET DocID = @.randc WHERE DocID = @.newc
>> David
> Change the column to an IDENTITY value. SQL Server automates the
> generation of the next value. You may have to seed the identity value
> using the MAX(ID) + 1 in the table.
Or by using DBCC CHECKIDENT, which should do the same job.

AutoNumber Primary Key

We are testing the upload of an Access 2002 data database to SQL Server
2000. Some of the tables had AutoNumber fields that were Random (due to it
being a replicated table in Access). The upload created triggers similar to
the example below. However, Access applications fail on insert because the
primary key field is not populated until the trigger runs. Any help is
appreciated.
CREATE TRIGGER T_AssessmentDocs_ITrig ON dbo.AssessmentDocs FOR INSERT AS
SET NOCOUNT ON
DECLARE @.randc int, @.newc int /* FOR AUTONUMBER-EMULATION CODE */
/* * RANDOM AUTONUMBER EMULATION CODE FOR FIELD 'DocID' */
SELECT @.randc = (SELECT convert(int, rand() * power(2, 30)))
SELECT @.newc = (SELECT DocID FROM inserted)
UPDATE AssessmentDocs SET DocID = @.randc WHERE DocID = @.newc
David
David C wrote:
> We are testing the upload of an Access 2002 data database to SQL
> Server 2000. Some of the tables had AutoNumber fields that were
> Random (due to it being a replicated table in Access). The upload
> created triggers similar to the example below. However, Access
> applications fail on insert because the primary key field is not
> populated until the trigger runs. Any help is appreciated.
> CREATE TRIGGER T_AssessmentDocs_ITrig ON dbo.AssessmentDocs FOR
> INSERT AS SET NOCOUNT ON
> DECLARE @.randc int, @.newc int /* FOR AUTONUMBER-EMULATION CODE */
> /* * RANDOM AUTONUMBER EMULATION CODE FOR FIELD 'DocID' */
> SELECT @.randc = (SELECT convert(int, rand() * power(2, 30)))
> SELECT @.newc = (SELECT DocID FROM inserted)
> UPDATE AssessmentDocs SET DocID = @.randc WHERE DocID = @.newc
> David
Change the column to an IDENTITY value. SQL Server automates the
generation of the next value. You may have to seed the identity value
using the MAX(ID) + 1 in the table.
You can pull back the newly inserted identity value into the application
using the SCOPE_IDENTITY() function.
David Gugick
Imceda Software
www.imceda.com
|||David Gugick wrote:
> David C wrote:
> Change the column to an IDENTITY value. SQL Server automates the
> generation of the next value. You may have to seed the identity value
> using the MAX(ID) + 1 in the table.
Or by using DBCC CHECKIDENT, which should do the same job.

AutoNumber Primary Key

We are testing the upload of an Access 2002 data database to SQL Server
2000. Some of the tables had AutoNumber fields that were Random (due to it
being a replicated table in Access). The upload created triggers similar to
the example below. However, Access applications fail on insert because the
primary key field is not populated until the trigger runs. Any help is
appreciated.
CREATE TRIGGER T_AssessmentDocs_ITrig ON dbo.AssessmentDocs FOR INSERT AS
SET NOCOUNT ON
DECLARE @.randc int, @.newc int /* FOR AUTONUMBER-EMULATION CODE */
/* * RANDOM AUTONUMBER EMULATION CODE FOR FIELD 'DocID' */
SELECT @.randc = (SELECT convert(int, rand() * power(2, 30)))
SELECT @.newc = (SELECT DocID FROM inserted)
UPDATE AssessmentDocs SET DocID = @.randc WHERE DocID = @.newc
DavidDavid C wrote:
> We are testing the upload of an Access 2002 data database to SQL
> Server 2000. Some of the tables had AutoNumber fields that were
> Random (due to it being a replicated table in Access). The upload
> created triggers similar to the example below. However, Access
> applications fail on insert because the primary key field is not
> populated until the trigger runs. Any help is appreciated.
> CREATE TRIGGER T_AssessmentDocs_ITrig ON dbo.AssessmentDocs FOR
> INSERT AS SET NOCOUNT ON
> DECLARE @.randc int, @.newc int /* FOR AUTONUMBER-EMULATION CODE */
> /* * RANDOM AUTONUMBER EMULATION CODE FOR FIELD 'DocID' */
> SELECT @.randc = (SELECT convert(int, rand() * power(2, 30)))
> SELECT @.newc = (SELECT DocID FROM inserted)
> UPDATE AssessmentDocs SET DocID = @.randc WHERE DocID = @.newc
> David
Change the column to an IDENTITY value. SQL Server automates the
generation of the next value. You may have to seed the identity value
using the MAX(ID) + 1 in the table.
You can pull back the newly inserted identity value into the application
using the SCOPE_IDENTITY() function.
David Gugick
Imceda Software
www.imceda.com|||David Gugick wrote:
> David C wrote:
> Change the column to an IDENTITY value. SQL Server automates the
> generation of the next value. You may have to seed the identity value
> using the MAX(ID) + 1 in the table.
Or by using DBCC CHECKIDENT, which should do the same job.

Autonumber or unidue id generation

Hi,
I am using a relation(table) which has a artificial key. I want to use this key as the primary key hence is unique. What datatype is associated with this attribute in MS SQL 2000. How can I generate unique id everytime I add a new record to this table ?
Thanks
-SudhakarHi,

I am using a relation(table) which has a artificial key. I want to use this key as the primary key hence is unique. What datatype is associated with this attribute in MS SQL 2000. How can I generate unique id everytime I add a new record to this table ?

Thanks
-Sudhakar

Make the datatype int and set the Identity constraint on that column.
Joydeep|||Your two best choices are either an Identity column (integer), or a GUID with the default set to NewID().|||I would STRONGLY recommend using the GUID if that option is available to you. IDENTITY values are fine for many purposes, and are easy for legacy code to manage, but GUID values are much simpler in the long run. They are easier to use, easier to generate, easier to manage, and very nearly foolproof, at least in my experience.

-PatP|||Well, I use GUIDs almost exclusively, but I don't know that I would recommend them as strongly as Pat. They do have some drawbacks, and I am not talking about their size or the fact they they are difficult to type (stupid arguments...). One of my pet peeves is that I can't apply aggregate functions such as MAX and MIN to GUIDs, which, believe or not, can be handy thing to do some times, such as when eliminating duplicates. You have to cast the GUID as char(36) first, which throws any indexes out the window.

autonumber is resetting

i am using autonumber as a primary key in one table. in my app., row from that table will be moved to another table after some time but that autonumber is important. when there are no any data in first table, and new row is inserted, autonumber starts from 1 which i don't want as there will be data redundancy when it will be moved to another table. so is there any way i can force the autonumber to start from previous value rathe than 1?Are you using an IDENTITY column? If so, I do not understand why you would have the problem you describe.|||i am using identity datatype.

yeah, it's strange. i added that data via webform interface and it was 1. then i tried adding directly in db but it gave me 10 as new value which is correct.

so just wondering if there is any settings i need to use just to make sure that it doesn't happen again.

AutoNumber Column and ...

Hi *.*
I plan to crate a database and want to know if it's good to use autonumber
columns as my primary key or I should generate the numbers myself?
Also, If I want to replicate the DB, is it ok to use autonumber columns?
At last, Is there any way I can manage the autonumber start number? Means
autonumbering starts at 100 or 300000 instead of 0?
Thanks for your help,
HOA
Hoa wrote:

> Hi *.*
> I plan to crate a database and want to know if it's good to use autonumber
> columns as my primary key or I should generate the numbers myself?
> Also, If I want to replicate the DB, is it ok to use autonumber columns?
> At last, Is there any way I can manage the autonumber start number? Means
> autonumbering starts at 100 or 300000 instead of 0?
> Thanks for your help,
> HOA
>
I suggest you take a step back and spend a month researching all this
along with getting your database professionally designed. Every one of
those questions are so "depends" in nature that the very fact that you
asked them tells me you don't have a good enough grasp of the situation
to appreciate the answers.
But, quickly:
1) Depends.
2) Sorta. Depends.
3) Yes.
There is an entire section in the Books Online that is called
"Replication Data Considerations" with a topic "Using IDENTITY Values".
Have you not even bothered to read that section prior to posting your
very open ended question?
Zach
|||Identity columns are fine for PK... as long as you plan on keeping your identity values unique. PK values MUST be unique; Identity does not explicitly enforce uniqueness. Identity columns are good for PKs in the fact that they are INTEGER datatype. This d
atatype is small, so it works well w/ indexes (PK defaults to unique, clustered)
Identity columns may need to be set to 'NOT FOR REPLICATION' in certain situations. See Books Online: Replication topology & NOT FOR REPLICATION for more info.
Yes, you can start an Identity value at a number greater than 0 or 1... you declare it with the IDENTITY(10,5) clause (10 being the 'seed' value, 5 being the increment.
"Hoa" wrote:

> Hi *.*
> I plan to crate a database and want to know if it's good to use autonumber
> columns as my primary key or I should generate the numbers myself?
> Also, If I want to replicate the DB, is it ok to use autonumber columns?
> At last, Is there any way I can manage the autonumber start number? Means
> autonumbering starts at 100 or 300000 instead of 0?
> Thanks for your help,
> HOA
>
>
|||Oh boy. Books Online is your friend, don't let it be a stranger. These
issues are all covered in the documentation.
Your choice of a primary key depends on more factors than "it's good"... see
for a bit of my own opinion.
Using an IDENTITY in a replication scenario is okay, depending on what type
of replication. It will not work in merge replication, for example, since
IDENTITY can't guarantee uniqueness from two different database sources.
As for the identity, yes see the CREATE TABLE and DBCC CHECKIDENT tables in
Books Online. If the table hasn't been created:
CREATE TABLE Splunge
(sid INT IDENTITY(30000, 1))
INSERT Splunge DEFAULT VALUES
INSERT Splunge DEFAULT VALUES
SELECT * FROM Splunge
GO
DROP TABLE Splunge
Once again, please become familiar with Books Online. All of the questions
are answered, and then some, in the documentation you already have available
to you.
http://www.aspfaq.com/
(Reverse address to reply.)
"Hoa" <newpoorguy@.yahoo.com> wrote in message
news:eMTZ#DkeEHA.2804@.TK2MSFTNGP11.phx.gbl...
> Hi *.*
> I plan to crate a database and want to know if it's good to use
autonumber
> columns as my primary key or I should generate the numbers myself?
> Also, If I want to replicate the DB, is it ok to use autonumber columns?
> At last, Is there any way I can manage the autonumber start number? Means
> autonumbering starts at 100 or 300000 instead of 0?
> Thanks for your help,
> HOA
>
|||Using identity columns in replication is supported and as other posters have
indicated this is covered in BOL. The exact use of identities in replication
depends on hte type of replication you have selected, but if for example you
were to do a merge publication, another tab appears on the article
properties which allows you to have SQL Server assign ranges to publisher
and subscriber which ensures there is no overlap in assigned numbers - this
is enforced by check constraints. You can alternatively manage the identity
ranges yourself and Michael Hotek shows how to do this on his site
(http://www.mssqlserver.com/replicati...h_identity.asp).
HTH,
Paul Ibison

autonumber

sql 2000

how can i set primary key to autonumber?
i created a form with this table,, i get error when trying to insert..
i want "id: column to autogenerate number
...................................... ............................

[Microsoft][ODBC SQL Server Driver][SQL Server]Cannot insert the value NULL into column 'id', table 'Guestbook.dbo.guestbook'; column does not allow nulls. INSERT fails.FYI:

You need to create the Primary Key using IDENTITY [ ( seed , increment )

Tim S

From BOL ( Books On Line)

CREATE TABLE
[ database_name.[ owner ] . | owner. ] table_name
( { < column_definition >
| column_name AS computed_column_expression
| < table_constraint > ::= [ CONSTRAINT constraint_name ] }

| [ { PRIMARY KEY | UNIQUE } [ ,...n ]
)

[ ON { filegroup | DEFAULT } ]
[ TEXTIMAGE_ON { filegroup | DEFAULT } ]

< column_definition > ::= { column_name data_type }
[ COLLATE < collation_name > ]
[ [ DEFAULT constant_expression ]
| [ IDENTITY [ ( seed , increment ) [ NOT FOR REPLICATION ] ] ]
]
[ ROWGUIDCOL]
[ < column_constraint > ] [ ...n ]|||is it possible to alter the table or column to make that changes?|||I have not found a way to alter the Table to make the change.

If use use the Enterprise Manager to change the column it creates a new table and copies the data into it and deletes the old table an renames the new table to match the old table name.

Tim S|||thanks