Click here to Skip to main content
15,888,461 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've been attempting to retrieve a table from the SQL DB based on user inputs, but I'm encountering the following error: "Format of the string does not conform to specification starting at index 0".

The query I'm using is
C#
"SELECT * FROM @Tablename WHERE Created_On >= '@StartDate' AND Created_On <= '@EndDate';";

I have parametrised the table name, start date, and end date. They will be based on the user's inputs. This query works fine in the SSMS server if I run it in the query editor by giving the desired inputs.

I'm storing the start date and end date in string format, and the Created_On column is of the the datatype [smalldatetime].

The connection string I'm using is in the format
C#
String connectionString = "SERVER NAME;Initial Catalog=DATABASE NAME;User ID=USERNAME;Password='PASSWORD';TrustServerCertificate=True;";


What I have tried:

I had to run this query in SSMS query editor with some desired input and it was working fine.
Posted
Updated 13-Apr-24 7:34am
v3

1 solution

Your command string is wrong:
SQL
SELECT * FROM @Tablename WHERE Created_On >= '@StartDate' AND Created_On <= '@EndDate';
Does not include the parameter values for @StartDate and @EndDate in the eventual query, in includes the literal strings '@StartDate' and '@EndDate' in the string.
Try taking off the quotes and see what happens then:
SQL
SELECT * FROM @Tablename WHERE Created_On >= @StartDate AND Created_On <= @EndDate;


But ... don't store dates in string form: they are very prone to errors. If your DB contains the string date "01-02-03" did the user who entered it mean "1st Feb 2003", "2nd Jan 2003", or "3rd Feb 2001"? They are all valid interpretations of that date.
And it gets worse when you want to compare dates: string comparisons are always done character by character and the result of the comparison if based on the first difference in characters. So depending on what format the data is entered in will determine the sort order. And worse, that's assuming the date isn't entered with a month name instead of a number, and that it's not been entered by a French or German person!

Always store information in the most appropriate variable type: INT, DECIMAL, or FLOAT for numbers, DATE, DATETIME, or DATETIME2 for dates and timestamps.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900