SQL Server TSQL Concat with Format using Different Types?

vaj7vani  于 2023-08-02  发布在  其他
关注(0)|答案(2)|浏览(116)

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

hts6caw3

hts6caw31#

I am assuming that the error you are having is that you're using a function call ( CONCAT ) directly inside the CREATE 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:

CREATE TABLE table1
(
  mydatetime datetime,
  myamount int,
  mydesc varchar(10)
)


ALTER TABLE table1
ADD computed_key AS (CONVERT(varchar(8), mydatetime, 112) + mydesc + CONVERT(varchar(30), myamount));

CREATE UNIQUE INDEX ixuq ON table1(computed_key);

fiddle

jhiyze9q

jhiyze9q2#

Create index:

CREATE CLUSTERED INDEX My_Index ON Table1 (
mydatetime,mydesc,myamount)

Or you can add unique constrain in table

ALTER TABLE table1 
ADD UNIQUE (mydatetime,mydesc,myamount)

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.

ALTER TABLE table1 
ADD mynewcolumn AS CONCAT(FORMAT(mydatetime, 'yyyyMMdd'), mydesc, FORMAT(myamount, 'N', 'en-US'))
ALTER TABLE table1 
ADD UNIQUE (mynewcolumn)

OR

CREATE CLUSTERED INDEX My_Index ON Table1 (mynewcolumn)

相关问题