Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/68.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 如何将常规条件添加到sp select?_Sql_Sql Server_Tsql - Fatal编程技术网

Sql 如何将常规条件添加到sp select?

Sql 如何将常规条件添加到sp select?,sql,sql-server,tsql,Sql,Sql Server,Tsql,我真的不知道在这种情况下该怎么办,所以不要太苛刻 如果我有自己的选择: declare @Id uniqueidentifier = 'some parent guid' declare @Type int = 1 -- can be 1, 2 or 3 declare @UserType varchar(max) --can be 0, anything else than 0, or all users at once if(@Type = 1) set @UserType = 'and

我真的不知道在这种情况下该怎么办,所以不要太苛刻

如果我有自己的选择:

declare @Id uniqueidentifier = 'some parent guid'
declare @Type int = 1 -- can be 1, 2 or 3
declare @UserType varchar(max) --can be 0, anything else than 0, or all users at once

if(@Type = 1)
set @UserType = 'and UserType <> 0'
if(@Type = 2)
set @UserType = 'and UserType = 0'
if(@Type = 3)
set @UserType = ''
    select * from users where parentId = @Id + @UserType 
如果条件是通用的,该怎么办?我真的需要创建3个不同的Sp吗

您可以使用AND/OR逻辑来模拟where子句中的If else条件。试试这样的

select * from users 
where
parentid= @id 
and 
(
(@Type = 1 and UserType <> 0)
or 
(@Type = 2 and UserType = 0)
or 
(@Type = 3)
)

不同的select语句效率最高,因为每个语句都是一个根本不同的查询。如果静态SQL变得笨拙,请使用动态SQL。下面是一个使用中的技术的参数化示例


不同的select语句效率最高,因为每个语句都是一个根本不同的查询。下面是一个动态SQL示例,使用
declare @Id uniqueidentifier = 'some parent guid'
declare @Type int = 1 -- can be 1, 2 or 3
Declare @UserType varchar(max) --can be 0, anything else than 0, or all users at once
Declare @sql nvarchar(max)

if(@Type = 1)
set @UserType = ' and UserType <> 0'
if(@Type = 2)
set @UserType = ' and UserType = 0'
if(@Type = 3)
set @UserType = ''

set @sql = 'select * from users where parentId ='''+ cast(@Id as varchar(25))+''''+ @UserType 

--Print @sql

Exec sp_executesql @sql
declare @sql nvarchar(MAX) = N'select * from users where parentId = @Id';
declare @Id uniqueidentifier = 'some parent guid';
declare @Type int = 1; -- can be 1, 2 or 3
declare @UserType varchar(max); --can be 0, anything else than 0, or all users at once

SET @sql = @sql + CASE @Type
    WHEN 1 THEN N' and UserType <> 0'
    WHEN 2 THEN N' and UserType = 0'
    WHEN 3 THEN N'' END;

EXEC sp_executesql
      @sql
    , N'@Id uniqueidentifier'
    , @Id = @Id;