0

I'm using what I consider to be very standard C# and T-SQL code to populate a column of datatype char(1) based on a C# enum with char values :

I am seeing an asterisk * written to db when a C should be written -- but I have been unable to find a consistent repo and I have no idea how this could happen.

Some questions are how could a row be inserted into my db that includes a value not present in my enum ? Does the asterisk have any special meaning in this context ?

Here's representative code - stripped-down for readability :

CREATE TABLE [MY_TABLE](
    [ID] [bigint] IDENTITY(1,1) NOT NULL,
    [STATUS] [char](1) NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


CREATE PROCEDURE [INSERT_TO_MY_TABLE]
(
   @status [char](1)
)
AS
BEGIN
  INSERT INTO [MY_TABLE]
  (
    [STATUS]
  )
  VALUES
  (
     @status
  )
END


public enum Status
{
    Adult = 'A',
    Juvenile = 'J',
    Child = 'C'
}
Statu status = Status.Child;
using (var command = connection.CreateCommand())
{
    command.CommandText = $"INSERT_TO_MY_TABLE";
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.Add(new SqlParameter($"@status", (char)status));
    command.ExecuteNonQuery();
}
BaltoStar
  • 8,165
  • 17
  • 59
  • 91
  • There is something else we are not seeing in your code writing an '*' to the table. With the snippet you posted, this could never happen. – Ross Bush Sep 21 '19 at 01:11
  • Possible duplicate of [Why we can't have "char" enum types](https://stackoverflow.com/questions/572963/why-we-cant-have-char-enum-types) – Ross Bush Sep 21 '19 at 01:58
  • If you need to deal with characters I'd suggest either using constants or create a class with a `char` property and a set of static instances for the allowed char values instead of using an `enum`. – juharr Sep 21 '19 at 03:17
  • @juharr what's wrong with using `enum` with `char` values ? – BaltoStar Sep 23 '19 at 18:14

1 Answers1

0

It looks like you have Status and StatusEnum active in your code - two different unrelated Enums

You want to change StatusEnum to Status

Also a string cast could generate the value "Child" instead of 'C' as an FYI.

status.ToString().Substring(0, 1) - would pull the first char of "Child" not the value of 'C'

Sql Surfer
  • 1,344
  • 1
  • 10
  • 25