ASP.NET

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''' WHERE orderId = '') AS Value

washble2 2026. 3. 20. 00:18

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''' WHERE orderId = '') AS Value

 

 

위와 같은 오류가 아래의 코드를 했을 때 일어났습니다.

FormattableString sql = $"SELECT EXISTS (SELECT 1 FROM {dbTable} WHERE orderId = {productId}) AS Value";
int exists = await _dbContext.Database.SqlQuery<int>(sql).SingleAsync();

 

이유는 dbTable을 변수로 넣으려고 해서 그렇습니다.

이를 해결하기 위해서는 dbTable을 명시적으로 넣어야하는데 dbTable  매번 바껴야 한다면 아래와 같이 변경하면 작동합니다.

 

// @p를 사용해서 값 넣기
string sql = $"SELECT EXISTS (SELECT 1 FROM {dbTable} WHERE orderId = @p0) AS Value";
int exists = await _dbContext.Database.SqlQueryRaw<int>(sql, orderId).SingleAsync();

// 변수가 여러개라면
string sql = $"SELECT EXISTS (SELECT 1 FROM {dbTable} WHERE orderId = @p0 AND updateDate = @p1) AS Value";
int exists = await _dbContext.Database.SqlQueryRaw<int>(sql, orderId, updateDate).SingleAsync();