PDA

View Full Version : مشکل در استفاده از case در بخش where یک select



احمد سامعی
یک شنبه 10 اردیبهشت 1391, 12:30 عصر
سلام
من یک کوئری به شکل زیر نوشتم. وقتی که مقدار نال پاس می کنم باید همه رکوردها بازگشت داده بشه اما فقط چند تا رو بر می بازگشت می ده و وقتی مقدار @deskId ست می کنم هیچ مقداری بازگشت داده نمی شه


select * from DocumentTB
WHERE
case when DocumentTB.customerType = 3 then COALESCE(@deskId, DocumentTB.customerId)
when DocumentTB.customerType < 2 then COALESCE(@commonId, DocumentTB.customerId)
else DocumentTB.customerId end
اینجوری هم نوشتم باز هم همونجوری

(DocumentTB.customerId =
case DocumentTB.customerType
when 0 then COALESCE(@commonId, DocumentTB.customerId)
when 1 then COALESCE(@commonId, DocumentTB.customerId)
when 2 then DocumentTB.customerId
when 3 then COALESCE(@deskId, DocumentTB.customerId)
end)

من sql server 2008 استفاده می کنم

Reza_Yarahmadi
یک شنبه 10 اردیبهشت 1391, 22:33 عصر
دستور دومی که نوشتید به نظر مشکلی نداره
SELECT * FROM DocumentTB
WHERE
DocumentTB.customerId =
CASE DocumentTB.customerType
WHEN 0 THEN COALESCE(@commonId, DocumentTB.customerId)
WHEN 1 THEN COALESCE(@commonId, DocumentTB.customerId)
WHEN 3 THEN COALESCE(@deskId, DocumentTB.customerId)
ELSE DocumentTB.customerId
END
داده های جدولتون رو چک کنید شاید مشکل ازاون باشه.
در ضمن نوع داده 2 پارامتر و customerId باید یکی باشه ، ممکنه نوع داده پارامترها رشته ای باشه و شما مقدار "" رو براش بفرستید که این باعث میشه مقدار صفر برگردونه و دستور شما خطای منطقی بده.

احمد سامعی
دوشنبه 11 اردیبهشت 1391, 11:40 صبح
ممنون نوع داده اشتباه زده بودم یکی smallint بود و یکی int اما مشکل از این هم نبود. در یک بخش دیگه از where اشتباهی یک فیلد بر اساس یک فیلد دیگه گذاشته بودم اشتباه در نام های مشابه
مشکل حل شد.
البته باید مثل زیر بنویسم چون اگر مثل بالا باشه تمام رکوردها بازگشت می شه
AND (DocumentTB.customerId =
case
when DocumentTB.customerType < 2 and @commonId is not null then @commonId
when DocumentTB.customerType = 3 and @deskId is not null then @deskId
when @deskId is null and @commonId is null then DocumentTB.customerId
end)