I have a stored procedure that uses a variable called @Command (nvarchar(MAX)). I then add parameters accordingly based on given input.
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 is declared as an int, and in the table it is an int. When I try
where EIKSSC.CaseFileID = ' + @CaseFileID + ' '
then the value doesn’t even show (in the error it looks like "EIKSSC.CaseFileID= '" )
I just don’t get it.
NOTE: SQL Server 2008 Management Studio
It’s because @CaseFileID is VARCHAR even though you don’t show it.
Your
IFshould beAnd if even that doesn’t work, then you need to swap to LEFT joins because INNER JOINs will remove records that cannot be matched in the other 2 tables.
Finally, because CaseFileID is an int, you don’t need the quotes. Even though SQL Server will implicitly cast ‘9’ to the integer 9 in the
WHEREclause, it’s just not necessary.