1

I have a table of stock quotes, and dates:

StockID QuoteID QuoteDay    QuoteClose
---------------------------------------
5         95    2018-01-03    1.080
5         96    2018-01-04    1.110
5         97    2018-01-05    1.000
5         98    2018-01-06    1.030
5         99    2018-01-07    1.010
5        100    2018-01-08    0.899
5        101    2018-01-09    0.815

I create a clustered index to manipulate the data but am running into duplicate key errors with the index

CREATE UNIQUE CLUSTERED INDEX MACD_IDX ON #TBL_MACD_LOOP (StockId, QuoteId)

Different combinations of StockID and QuoteID will result in the same output:

For example (StockID, QuoteID) of (5, 11) and (51, 1) both produce an index of 511.

My solution is to add "-" between StockId and QuoteId.

Now (5, 11) produces 5-11 and (51, 1) produces 51-1.

How do I combine strings with values?

1
  • The full error message you will include the values SQL Server finds as a duplicate key. I expect you will find there is more than one row when you run SELECT * FROM #TBL_MACD_LOOP WHERE StockID = <value1> AND QuoteID = <value2>; Commented Apr 29, 2018 at 20:50

1 Answer 1

1

No, you are definitely mistaken.

The combinations for (StockId, QuoteId) of (5, 11) and (51, 1) are two DISTINCTLY different pairs of values.

They are NOT combined into a single value (of 511 as you assume) when creating the index entry. Those are two different values and therefore can co-exist in that table - no problem.

To prove this - just run this INSERT statement:

INSERT INTO #TBL_MACD_LOOP(StockId, QuoteId, QuoteDay, QuoteClose)
VALUES (5, 11, '20180505', 42.76), (51, 1, '20180505', 128.07)

Even with your unique index in place, this INSERT works without any trouble at all (assuming you don't already have one of these two pairs of values in your table, of course)

Sign up to request clarification or add additional context in comments.

2 Comments

Since I'm getting the duplicate key error, what's the best way to check for duplicates?
@Coding_Newbie: if inserting one pair of values fails - just run SELECT * FROM #TBL_MACD_LOOP WHERE StockId = xx AND QuoteId = yy and find your culprit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.