【问题标题】:Stored procedure doesn't return any row but same query returns proper data存储过程不返回任何行,但相同的查询返回正确的数据
【发布时间】:2016-06-11 01:53:39
【问题描述】:

这是我的存储过程:

CREATE PROC [SPmainReport]
@startDate date = null,
@endDate date = null,
@customerName varchar = null,

AS
SELECT Distinct
    VI.Code as CustomerCode, VI.Name as CustomerName, VI.Area as CustomerArea, VI.[Address] as [address], CP.ProductName as ProductName, CP.ProductQuantity as Quantity
from 
VendorTrading VT inner join CustomerProducts CP on VT.Id = CP.VendorTradingId inner join VendorInfo VI on VT.VendorId = VI.Id
where
 (VT.Tradedate between isnull(@startDate,VT.Tradedate) and isnull(@endDate,VT.Tradedate))
 and VI.Name = ISNULL(@customerName, VI.Name)

执行时它不返回任何值,但如果我执行此查询:

    SELECT Distinct
    VI.Code as CustomerCode, VI.Name as CustomerName, VI.Area as CustomerArea, VI.[Address] as [address], CP.ProductName as ProductName, CP.ProductQuantity as Quantity
from 
VendorTrading VT inner join CustomerProducts CP on VT.Id = CP.VendorTradingId inner join VendorInfo VI on VT.VendorId = VI.Id
where
 (VT.Tradedate between isnull(@startDate,VT.Tradedate) and isnull(@endDate,VT.Tradedate))
 and VI.Name = ISNULL('John', VI.Name)

它返回完全需要的数据。我完全困惑为什么会这样。完全没有区别。我确保脚本在同一个数据库上运行,并且它还包含完美的数据。这里是SP执行脚本:

USE [E:\SANDWICH3\ABC\BIN\DEBUG\DATABASE\ABC.MDF]
GO

DECLARE @return_value Int

EXEC    @return_value = [dbo].[SPmainReport]
    @startDate = '2015-12-25',
    @endDate = '2015-12-25',
    @customerName = N'John'

SELECT  @return_value as 'Return Value'

GO

我注意到的一个更奇怪的事情是,如果我只用日期而不是名称来修改这个 SP 和限制条件。那么它工作正常。 我正在开发 SQL Server 的 Visual Studio 2013 接口。不是管理工作室(以防万一)

【问题讨论】:

标签: sql sql-server visual-studio stored-procedures


【解决方案1】:

在 SQL Server 中,总是在使用 varchar()char() 及相关类型时使用长度参数:

CREATE PROCEDURE SPmainReport (
    @startDate date = null,
    @endDate date = null,
    @customerName varchar(255) = null
)
BEGIN
    . . . 
END;

大多数客户名称可能不止一个字符。

【讨论】:

  • 因为如果您指定长度,那么@customerName varchar 最终会正好--1--字符长!跨度>
  • 天哪!你救了我整个晚上。谢谢十亿。这是多么愚蠢的错误。感谢上帝,我没有浪费我更多的时间并在这里问。我已经浪费了几个小时来弄清楚。非常感谢@Gordon Linof
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多