views:

194

answers:

2

I am working on a legacy database. I am not able to change the schema :( in a couple of tables the primary key uses multiple columns.

In the app I read the data in each row into a table the user then updates the data and I write the data back into the table.

Currently I concatenate the various PK columns and store them as a unique id for when I put the data back into the table.

Now I was wondering if there is a more efficient way to do that. Coming from a mySQL background I am not aware of any but thought SQL Server 2005 may have a function

SELECT PRIMARYKEY() as pk, ...  FROM table WHERE ...

the above would select the key that the database engine uses as the primary key for the given record

I searched and couldn't find anything. Its probably just me being fussy but I don't like the concatenation trick.

DC

+1  A: 

"Currently I concatenate the various PK columns and store them as a unique id for when I put the data back into the table." Can't you just store the pk as two columns in the target table and use that to join back to the two columns on the source table?

What benefit is concatenating giving you here?

StarShip3000
He probaly uses it as a key in some kind of data structure in his programming language. Not in the database.
idstam
Its a legacy database that I was given, the original designer chose to use multiple columns as the primary key. There is no second table. I simply take the data out present it to the user and put any changes back. unfortunately I am not at liberty to change the design of the table.
DeveloperChris
+1  A: 

In SQL Server, there is no equivalent of PRIMARYKEY() that I would be aware of, really. You can consult the system catalog views to find out which columns make up the primary key, but you can't just simply select the primary key value(s) with a function call.

I would agree with StarShip3000 - what do you concatenate your PK values for? While I don't think a compound primary key made up of several columns is necessarily a very good idea, if it's a legacy system and you can't change it, I wouldn't bother concatenating the PK values on read, and then having to split them apart again when you write your data back. Just leave the structure as it is - compound keys aren't generally recommended, but they are indeed supported, no problem.

marc_s
I concatenate the keys on read because its easier (in the sql statement ie: select col1 + col2 as uid from blah) I then store the resulting string as a unique id in the web form. when updating the table I compare the unique id to the concatenation of the columns in the where statement ie: update blah where col1 + col2 = uid. that way the concatenation is all done in sql and there is less chance that someone changes the ordering and breaks it later. at least thats the theory. The reason its ugly is there is 5 ints and one varchar in the primary key.
DeveloperChris