简体   繁体   English

在SQL Server中使用字符串参数时无法返回正确的查询

[英]Unable to return correct query when using string parameter in SQL Server

I have a simple employee table 我有一个简单的员工表

员工表

and here is the data 这是数据

员工表数据

When I try to run a query with string parameter it doesn't return anything although it has correct parameter 当我尝试使用字符串参数运行查询时,尽管它具有正确的参数,但不返回任何内容

用正确的字符串参数查询

and when I try to change it to double quote ", it returns an error 当我尝试将其更改为双引号“时,它返回错误

查询包含参数“”的字符串参数

Have I missed something? 我错过了什么吗? Thanks in advance 提前致谢

Your first query is correct. 您的第一个查询是正确的。 The problem is the data. 问题是数据。 The empid field has something other than '10002' in the field. empid字段中的字段不是'10002' You can investigate this in various ways: 您可以通过多种方式对此进行调查:

select length(empid), '|' + empid + '|'
from employee

This will provide information about unexpected characters that you might not see. 这将提供有关您可能看不到的意外字符的信息。 The length for the field should be 6. The output for the second column should be "|100002|". 该字段的长度应为6。第二列的输出应为“ | 100002 |”。

If an extra character at the beginning or end of the field is the issue, then: 如果在该字段的开头或结尾出现多余的字符,则:

where empid = '%100002%'

solves the problem. 解决了问题。 However, there is a big potential performance difference, because this query cannot take advantage of the primary key index. 但是,潜在的性能差异很大,因为此查询无法利用主键索引。 So, you want to fix the data. 因此,您要修复数据。

You might have confused the letter zero with the number, or capital "I" or lower case "l" for 1. These can be harder to spot, but you can use lower() and upper() to help find such issues. 您可能已经将字母0与数字或大写字母“ I”或小写字母“ l”混淆为1。这可能很难发现,但是可以使用lower()upper()来帮助发现此类问题。

You could have a special char, like a carriage return, at the end of the value. 您可以在值的末尾使用特殊字符,例如回车符。 Use the query below to check if there are some of those cases in your table. 使用下面的查询检查表中是否存在某些情况。

    SELECT
       EmpId,
    --   convert(int, EmpId) AS EmpId_INT,
       LEN(EmpId) AS Len_EmpId
    FROM
       Employee
    -- WHERE
    --   LEN(EmpId) <> LEN(convert(int, EmpId))
    ORDER BY
       EmpId

If it's not mandatory, I suggest to change the "EmpId" data type to int. 如果不是强制性的,我建议将“ EmpId”数据类型更改为int。

您可以简单地将empId列的数据类型更改为Int而不是varchar。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM