問題描述
我的 SQL Server 中有一個表.目前我使用身份列來唯一標識每條記錄,但我不斷變化的需求需要以特定格式生成的唯一密鑰(由我的客戶指定).我試圖通過將一個唯一的整數(在每次插入時遞增)附加到我的客戶對我當前的解決方案不滿意的指定格式來從我的應用程序生成唯一鍵.如果我能被引導到更好的技術來解決我的問題而不是我當前的解決方案,那就太好了.
I have a table in my SQL Server. Currently I am using the identity column to uniquely identify each record but my changing needs required a unique key generated in a certain format (as specified by my client). I have tried to generate the unique key from my application by appending a unique integer (that is incremented on every insert) to the format specified my client is not satisfied with my current solution. It would be great if I can be directed to a better technique to solve my problem rather then my current solution.
格式如下:
PRN-YEAR-MyAppGeneratedInt
推薦答案
基本上,保留當前的 ??identity
列.這是您識別和管理表中行的最佳方式.
Basically, keep the current identity
column. That is the best way for you to identify and manage rows in the table.
如果客戶端需要另一個唯一鍵,則添加它.據推測,它將是一個字符串(假設它具有格式").您可以將鍵創建為生成的列.或者,您可能需要使用觸發器來計算它.
If the client needs another unique key, then add it. Presumably, it will be a string (given that it has a "format"). You can possibly create the key as a generated column. Alternatively, you may need to use a trigger to calculate it.
一般來說,整數更適合標識列,即使最終用戶從未看到它們.以下是一些優點:
In general, integers are better for identity columns, even if end users never see them. Here are some advantages:
- 它們對數據庫中行插入的順序進行編碼.例如,您可以獲取最后插入的行.
- 它們對于外鍵引用更有效(因為數字是固定長度的并且通常比字符串短).
- 當需要修復數據時,它們可以直接尋址一行.
這篇關于創建我的自定義唯一鍵的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!