sql查询使用where条件

sql查询使用where条件

问题描述:

我有4个变量从c#进入存储过程。我必须传递所有变量。这个变量可以有一个值或者为null。



如果特定变量为null,我需要选择表中的所有行(一些具有NULL值,一些有实际数据)。



如果变量不为null,我只需要选择变量与列匹配的行。

i试图给予



I have 4 variables coming into a stored procedure from c#. i must pass all the variables. This variables can either have a value or be null.

If the particular variable is null, I need to select all the rows in the table (some with NULL values, some with actual data).

If the variable is not null, I only need to select the rows where the variable matches a column.
i tried giving

SELECT FirstName FROM AdmissionTbl WHERE (City=@city or City is null) and (state=@state or state is null) and (religion=@religion or religion is null)and (marks=@marks or marks is null)





如果值是传递它工作,但如果它是null它不检索所有记录。

任何人都可以帮忙吗?



if a value is passed it works, but if it is null it is not retrieving all the records.
Can anyone helpme?

引用:

我试过给

SELECT FirstName FROM AdmissionTbl WHERE(City = @ city或City is null)和(state = @ state或者状态为null)和(religion = @ religion或religion为null)和(marks = @ marks或marks为null)

i tried giving
SELECT FirstName FROM AdmissionTbl WHERE (City=@city or City is null) and (state=@state or state is null) and (religion=@religion or religion is null)and (marks=@marks or marks is null)



你几乎是正确的但是变化很小


you are almost correct but a small change

SELECT FirstName FROM AdmissionTbl 
WHERE (@city is null or City=@city) 
and (@state is null or state=@state) 
and (@religion is null or religion=@religion) 
and (@marks is null or marks=@marks)



希望有所帮助你好!


Hope it helps you!


你好我们在这里查看我不知道你是如何建立你的桌子我创建了一个带有ID,名字,城市的表格,当城市匹配或城市为空时检索所有名字



Hi check here I don''t know how you build your table I have create a table with ID, Firstname,city and retrieving all firstname when city is matched or city is null

CREATE TABLE [dbo].[tblDemo]([id] [int] NOT NULL,[FirstName] [varchar](50) NULL,
[City] [varchar](50) NULL) ON [PRIMARY]





http://s8.postimage.org/4oukaxwtx/sql.jpg [ ^ ]





这是我的查询,当city为null或传递值时检索firstname



http://s8.postimage.org/4oukaxwtx/sql.jpg[^]


this is my query to retrieve the firstname when city is null or value is passed

Select FirstName From tbldemo Where city is null or city like 'RJY'





http://s4.postimage.org/e4qlni62l/results.jpg [ ^ ]