我有一个存储过程。
SELECT ADDRESS.ADDRESSID, NAME, DOORNO, STREET, STATE, COUNT(SUB.ADDRESSID) AS FREQUENCY
FROM ADDRESS
JOIN
(
(SELECT ADDRESSID FROM ADDRESS WHERE KEYWORD LIKE '%' + @name + '%')
UNION ALL
(SELECT ADDRESSID FROM ADDRESS WHERE KEYWORD LIKE '%' + @doorno + '%')
UNION ALL
(SELECT ADDRESSID FROM ADDRESS WHERE KEYWORD LIKE '%' + @street + '%')
UNION ALL
(SELECT ADDRESSID FROM ADDRESS WHERE KEYWORD LIKE '%' + @state + '%')
)
SUB
ON SUB.ADDRESSID=ADDRESS.ADDRESSID
GROUP BY ADDRESS.ADDRESSID, NAME, DOORNO, STREET, STATE
ORDER BY FREQUENCY DESC
当我手动执行此操作时,我得到了正确的结果。 让我们说这些是结果
╔════╦══════╦════════════════╦═════════════════════╦═══════╦═══════════╗
║ ID ║ NAME ║ DOORNO ║ STREET ║ STATE ║ FREQUENCY ║
╠════╬══════╬════════════════╬═════════════════════╬═══════╬═══════════╣
║ 4 ║ John ║ 29 ║ Police Station ║ DC ║ 3 ║
║ 1 ║ John ║ Door 13-9-16/A ║ patimeeda ║ NJ ║ 2 ║
║ 3 ║ Paul ║ Plot 304 ║ Near Police Station ║ NJ ║ 1 ║
╚════╩══════╩════════════════╩═════════════════════╩═══════╩═══════════╝
但是当我使用Sqldataadapter和数据集从C#代码调用此SP时,我总是得到频率为1 如下所示。
╔════╦══════╦════════════════╦═════════════════════╦═══════╦═══════════╗
║ ID ║ NAME ║ DOORNO ║ STREET ║ STATE ║ FREQUENCY ║
╠════╬══════╬════════════════╬═════════════════════╬═══════╬═══════════╣
║ 1 ║ John ║ Door 13-9-16/A ║ patimeeda ║ NJ ║ 1 ║
║ 3 ║ Paul ║ Plot 304 ║ Near Police Station ║ NJ ║ 1 ║
║ 4 ║ John ║ 29 ║ Police Station ║ DC ║ 1 ║
╚════╩══════╩════════════════╩═════════════════════╩═══════╩═══════════╝
排序对我来说非常重要。知道我失去这个的原因吗?
C#.NET代码
SqlCommand cmd = new SqlCommand("Add_GetAddressSearchResults", con);
cmd.CommandType=CommandType.StoredProcedure;
cmd.Parameters.Add("@name", SqlDbType.VarChar, 50).Value=addressModel.Name;
cmd.Parameters.Add("@doorno", SqlDbType.VarChar, 50).Value=addressModel.DoorNo;
cmd.Parameters.Add("@street", SqlDbType.VarChar, 50).Value=addressModel.Street;
cmd.Parameters.Add("@state", SqlDbType.VarChar, 50).Value=addressModel.State;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds= new DataSet();
da.Fill(ds);
ds.WriteXml("c:/ram.xls"); // to check the data
答案 0 :(得分:0)
如果你已经消除了其他明显的原因(不同的数据库,不同的查询......),我强烈怀疑你在ADDRESSID列中有NULL值,ANSI_NULLS配置不同。
我认为C#连接的默认值与SQL Server Management Studio中的默认值不同。
要对此进行测试,请尝试在手动执行查询时打开和关闭ANSI_NULLS,和/或尝试修改查询以按照您希望的方式显式处理NULL,例如类似的东西:
ON ISNULL(SUB.ADDRESSID,0)=ISNULL(ADDRESS.ADDRESSID,0)
您还可以尝试在存储过程中明确设置此(以及其他类似设置,如ANSI_PADDING)。
答案 1 :(得分:0)
我可能错了,但是您从子查询中提取的SUB
再次包含ADDRESS
的记录,ADDRESSID
上的内部联接可能会将频率设为1,除非SUB
包含的内容超过了ADDRESS
中的内容,您的正确结果将是因为传递的参数在ADDRESS
中为您提供了SUB
的超集