質問

I'm trying to insert new records into a table. The first field in the table is an supposed to be an autonumber, even though it isn't at the moment, and I am trying to run ExecuteScalar() to retrieve the MAX of that field (ELECT_BONUS_DFRL_SEQ_ID, if it is NULL or 0, I would like to make it 1, else make it MAX(e.ELECT_BONUS_DFRL_SEQ_ID) + 1.

I am not really familiar with SQL all that well, and I've done my best to try and format it correctly but I can tell I am off on something.

SELECT CASE 
        WHEN e.ELECT_BONUS_DFRL_SEQ_ID IS NULL OR MAX(e.ELECT_BONUS_DFRL_SEQ_ID) < 1
        THEN e.BONUS_DFRL_SEQ_ID = '1'
        ELSE MAX(e.ELECT_BONUS_DFRL_SEQ_ID) + 1
    END AS ELECT_BONUS_DFRL_SEQ_ID
FROM ELECT_BONUS_DFRL AS e
GROUP BY e.ELECT_BONUS_DFRL_SEQ_ID;

SQLFiddle - It keeps saying there is an error at the = in my THEN statement.

Now, I thought about creating a variable like @NextID and using that to hold the value of 1 or the MAX + 1, but I'm not sure if that would interfere with my ExecuteScalar() in my program.

I also am not sure if it's allowed to assign values to the columns like that, and by that I mean: THEN e.BONUS_DFRL_SEQ_ID = '1'

The code in my program is :

    Dim sql As String = "SELECT MAX(BONUS_SEQ_ID) FROM ELECT_BONUS_DFRL_SEQ_ID;"
    Dim maxCmd As New SqlCommand(sql, conn)
    nextID = Convert.ToInt32(maxCmd.ExecuteScalar())

I am hoping nextID will hold the next number in the sequence.

Example:

+------------------+--------------+
|ELECT_BONUS_SEQ_ID|  Percentage  |
+------------------+--------------+
|        1         |      100     |
+------------------+--------------+
|     nextID       |              |  <- new record to insert

PS - If you're looking at the SQLFiddle and scratching your head at the Data types, all of the varchar fields will be encrypted data, and the guy who set up the DDL didn't make the SEQ_ID an INT & IDENTITY so it doesn't autoincrement. (this will be resolved in the future, I am hoping.)

If anyone has any ideas, please let me know. Also, if you care to shed some light as to why it wouldn't work for the ways I tried please do!

役に立ちましたか?

解決

It looks like you're trying to update the source data within a SELECT which is not possible. Did you mean this?

SELECT CASE 
        WHEN e.ELECT_BONUS_DFRL_SEQ_ID IS NULL OR MAX(e.ELECT_BONUS_DFRL_SEQ_ID) < 1
        THEN 1
        ELSE MAX(e.ELECT_BONUS_DFRL_SEQ_ID) + 1
    END AS ELECT_BONUS_DFRL_SEQ_ID
FROM ELECT_BONUS_DFRL AS e
GROUP BY e.ELECT_BONUS_DFRL_SEQ_ID;

If you are trying to update the source data then you need to do the UPDATE in one statement and the SELECT in another.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top