自从我做msSql以来已经有一段时间了,所以有人可以提醒我如何选择不同的ForeignKeyIDs的值吗?
当ForeignKeyID为1时,我想要选择大于10的值;然后我想在ForeignKeyID为2时选择大于20的值;当ForeignKeyID为3时,值大于30,等等......
我知道以下执行不起作用,因为我得到一个空结果,而我在我的表中看到(填充了数千条记录)我之前提到的条件存在。
var filter = string.Empty;
if (String.IsNullOrEmpty(tbName.Text))
{
filter += "Name LIKE '%" + tbName.Text + "%'";
}
if (String.IsNullOrEmpty(tbSifraTransakcije.Text))
{
if (!String.IsNullOrEmpty(filter))
{
filter += " AND ";
}
filter += "MiddleName LIKE '%" + tbMiddleName.Text + "%'";
}
if (String.IsNullOrEmpty(tbSurname.Text))
{
if (!String.IsNullOrEmpty(filter))
{
filter += " AND ";
}
filter += "Surname LIKE '%" + tbSurname.Text + "%'";
}
bsAllPeople.Filter = filter;
我认为我没有正确放置括号?
答案 0 :(得分:2)
我创建了一个示例表,并创建了一个通用查询,该查询将基于ForiegnKeyID和Value附加Where类:)
Create table Mytemp
(
ForeignKeyID int,
[Value] int
)
Insert into Mytemp values (1,10)
Insert into Mytemp values (2,20)
Insert into Mytemp values (3,30)
Insert into Mytemp values (4,40)
Insert into Mytemp values (5,50)
Insert into Mytemp values (6,60)
Insert into Mytemp values (7,70)
Insert into Mytemp values (8,80)
DECLARE @value INT
Declare @FKey INT
Declare @SQL varchar(max)
Declare @Where varchar(max)
Set @Where=''
set @SQL='SELECT [ForeignKeyID] ,[Value] FROM Mytemp'
DECLARE @db_cursor CURSOR
SET @db_cursor = CURSOR FOR SELECT [ForeignKeyID] ,[Value] FROM Mytemp
OPEN @db_cursor
FETCH NEXT
FROM @db_cursor INTO @FKey, @value
WHILE @@FETCH_STATUS = 0
BEGIN
If @Where=''
set @Where='(ForeignKeyID = '+Convert(varchar,@FKey) +' AND Value > '+Convert(varchar,@value) +')'
Else
set @Where=@Where+ ' OR ' +'(ForeignKeyID = '+Convert(varchar,@FKey) +' AND Value > '+Convert(varchar,@value) +')'
FETCH NEXT
FROM @db_cursor INTO @FKey, @value
END
CLOSE @db_cursor
DEALLOCATE @db_cursor
set @SQL=@SQL+' Where ' + @Where
Print (@SQL)
Exec (@SQL)
Drop table Mytemp
答案 1 :(得分:1)
您使用的是错误的逻辑运算符。大括号中每对条件之间的关系应为or
,而不是and
:
SELECT [ForeignKeyID]
,[Value]
FROM [tblMyTable]
WHERE (ForeignKeyID = 1 AND Value > 10) OR
(ForeignKeyID = 2 AND Value > 20) OR
(ForeignKeyID = 3 AND Value > 30)
请注意,使用一些数学技巧可以大大简化这种情况:
SELECT [ForeignKeyID]
,[Value]
FROM [tblMyTable]
WHERE ForeignKeyID IN (1, 2, 3) -- Or any other value you want to allow
AND Value > (10 * ForeignKeyValue)