Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 2005 如何在静态查询中使用之前验证输入参数??SQL server 2005_Sql Server 2005 - Fatal编程技术网

Sql server 2005 如何在静态查询中使用之前验证输入参数??SQL server 2005

Sql server 2005 如何在静态查询中使用之前验证输入参数??SQL server 2005,sql-server-2005,Sql Server 2005,考虑有两列的表1 table1: column1 int, column2 char 问题:用户可以为col1或col2或col1和col2输入有效的输入。因此,我需要验证用户输入,并在satic查询中使用这些正确的列 例如:如果两个输入都正确,那么查询将是: select * from table1 where column1=@col1 and column2 =@col2 如果只有col2有效,而col1不是valida,则: select * from table1 where

考虑有两列的表1

table1: column1 int, column2 char 问题:用户可以为col1或col2或col1和col2输入有效的输入。因此,我需要验证用户输入,并在satic查询中使用这些正确的列

例如:如果两个输入都正确,那么查询将是:

select * from table1 where column1=@col1 and column2 =@col2
如果只有col2有效,而col1不是valida,则:

select * from table1 where column2=@col2 

如何在静态查询中使用之前验证输入参数??在sql server 2005中,您的意思是:

Create Procedure Sp1( @Col1..., @Col2... )
As

-- if @Col1 is not valid, then set it to Null
If @Col1 <> <valid number or string or date> 
    Set @Col1 = Null

-- if @Col2 is not valid, then set it to Null
If @Col2 <> <valid number or string or date>
    Set @Col2 = Null

Select ...
From Table1
Where ( @Col1 Is Not Null Or @Col2 Is Not Null )
    And ( Col1 = @Col1 Or @Col1 Is Null )
    And ( Col2 = @Col2 Or @Col2 Is Null )
试试这个:

Create Procedure Sp1( @Col1..., @Col2... )
As

If @Col1 {is valid} AND @Col2 {is valid} 
BEGIN
    select * from dbo.table1 where column1=@col1 and column2 =@col2
END
ELSE @Col2 {is valid} 
BEGIN
    select * from dbo.table1 where column2=@col2 
END

RETURN 0
GO

小心使用@col1 IS NULL或@col1=col1技巧,不会使用索引。阅读以了解每种动态搜索方法的优缺点。我选择了,因为OP只列出了2个要搜索的条件,所以这样做似乎是可行的。

在这种情况下,看起来动态SQL将是最好的选择-您将根据参数的有效性生成WHERE子句,然后使用sp_executesql执行整个查询。

我提出了同样的想法。删除了我的+1谢谢你。谢谢你的回复。是的,与此类似。你能告诉我如何在使用前验证列吗?此方法不会使用索引,如果涉及到大表,将运行缓慢。谢谢。。但是我不想一次又一次地重复这个查询。因为,我的查询有n行。@Guru,您没有提供足够的查询详细信息,但是请阅读我链接到的文章。要使查询很好地执行,需要考虑很多因素。
Create Procedure Sp1( @Col1..., @Col2... )
As

If @Col1 {is valid} AND @Col2 {is valid} 
BEGIN
    select * from dbo.table1 where column1=@col1 and column2 =@col2
END
ELSE @Col2 {is valid} 
BEGIN
    select * from dbo.table1 where column2=@col2 
END

RETURN 0
GO