我有一个使用名为@Command (nvarchar(MAX))
的变量的存储过程。然后,我根据给定的输入相应地添加参数。
declare @Command nvarchar(max)
if(@CaseFileID IS NOT NULL)
BEGIN
select @Command='
select [ServerCredentialsID],[CaseFileID],EIKSLT.[LocationType],EPT.PaymentType,[TaskID],[DateActive]
,[LengthOfPurchase],[Username],[Password],[IPDomain],[Port],[DES],[Website],[AmountPaid],[Latitude]
,[Longitude],[HasAttachments],[TimeStamp],[CaseElement],[Temporary],[StatusID]
FROM Element17a_IKSServerCredentials EIKSSC
JOIN ElementsIKSLocationTypes EIKSLT ON EIKSSC.LocationBeingUsedID= EIKSLT.IKSLocationBeingUsedID
JOIN ElementsPaymentTypes EPT ON EIKSSC.PaymentMethodID=EPT.PaymentTypeID
where EIKSSC.CaseFileID='''+cast(@CaseFileID as nvarchar(MAX))+''' '
@CaseFileID声明为int,在表中它是一个int。当我尝试
where EIKSSC.CaseFileID = ' + @CaseFileID + ' '
然后该值甚至没有显示(在错误中它看起来像"EIKSSC.CaseFileID= '"
)
我只是不明白。
注意:SQL Server 2008 Management Studio
答案 0 :(得分:1)
这是因为@CaseFileID是VARCHAR,即使你没有显示它
您的IF
应为
if(@CaseFileID > '')
如果即使这样也行不通,那么你需要交换到LEFT连接,因为INNER JOIN将删除其他2个表中无法匹配的记录。
最后,因为CaseFileID是一个int,所以不需要引号。即使SQL Server将隐式地将'9'强制转换为WHERE
子句中的整数9,但它也没有必要。
declare @Command nvarchar(max)
if(@CaseFileID > '')
BEGIN
select @Command='
select [ServerCredentialsID],[CaseFileID],EIKSLT.[LocationType],EPT.PaymentType,[TaskID],[DateActive]
,[LengthOfPurchase],[Username],[Password],[IPDomain],[Port],[DES],[Website],[AmountPaid],[Latitude]
,[Longitude],[HasAttachments],[TimeStamp],[CaseElement],[Temporary],[StatusID]
FROM Element17a_IKSServerCredentials EIKSSC
LEFT JOIN ElementsIKSLocationTypes EIKSLT ON EIKSSC.LocationBeingUsedID= EIKSLT.IKSLocationBeingUsedID
LEFT JOIN ElementsPaymentTypes EPT ON EIKSSC.PaymentMethodID=EPT.PaymentTypeID
where EIKSSC.CaseFileID='+cast(@CaseFileID as nvarchar(MAX))