I get this error:
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '('
from this statement:
CREATE UNIQUE INDEX ixuq
ON table1 (CONCAT(FORMAT(mydatetime, 'yyyyMMdd'), mydesc, FORMAT(myamount, 'N', 'en-US')))
What I am trying to do is concat the date part of a datetime value, a varchar, and a decimal value into a unique varchar key.
Can anyone help with the syntax for this? I thought this would work in a single statement, but if it needs to be more than one, open to learning.
I'm using SQL Server 2022 Developer edition running on a local Windows desktop.
Thanks
2条答案
按热度按时间hts6caw31#
I am assuming that the error you are having is that you're using a function call (
CONCAT
) directly inside theCREATE UNIQUE INDEX
statement. In SQL Server, when creating an index, you can only reference columns from the table directly, not perform complex expressions or function calls.As already mentioned, you can create a computed column that concatenates the values you need, and then create a unique index on that computed column. Here's an example:
fiddle
jhiyze9q2#
Create index:
Or you can add unique constrain in table
You can't create index, constrain for column which not exists in table. For create constraint like in your example you need to add column with your code and than create unique constraint for it.
OR