简体   繁体   English

表值可选参数

[英]Table Value optional parameter

Is it possible to create a procedure with a table value parameter as an optional parameter.是否可以创建一个带有表值参数作为可选参数的过程。

I tried the following code:我尝试了以下代码:

CREATE PROCEDURE SP
@Table testteype = null READONLY
AS 
....

But I get this error:但我收到此错误:

Operand type clash: void type is incompatible with test type 

ps: I use sql server with C#.Net ps:我在 C#.Net 中使用 sql server

Table-Valued parameters always have an implicit value of an empty table.表值参数始终具有空表的隐式值。 So you can actually call that procedure without any parameters and it would execute but the table would be empty.因此,您实际上可以在没有任何参数的情况下调用该过程,它会执行但该表将为空。

So it doesn't really make sense to label a table-value parameter with a default value.因此,用默认值标记表值参数实际上没有意义。 Remove the "=null", check the table contents, and you should be good to go.删除“=null”,检查表内容,您应该很高兴。

Basically, having default value "= null" makes no sense and is the reason of the error.基本上,具有默认值“= null”是没有意义的,并且是错误的原因。

By default, @Table testteype gets value of an empty table.默认情况下, @Table testteype获取空表的值。 Thus, you may remove = null:因此,您可以删除 = null:

CREATE PROCEDURE SP
@Table testteype  READONLY
AS 
....

Reference: for a sample on how to use this with C# ADO.NET i would recommend to use this post - Using SQL Server's Table Valued Parameters参考:有关如何在 C# ADO.NET 中使用它的示例,我建议使用这篇文章 - Using SQL Server's Table Valued Parameters

--exa:
--create TYPE  Table_tt   as table(id int,name  varchar(10))

create table #a  (aid int,price int)
insert into #a (aid  ,price  )
select 1,10
union
select 2,50

create PROCEDURE SP
@Table_tt Table_tt  null READONLY     
AS 
 begin 
 select * into #tem from @Table_tt
 select * from #a where aid in(select id from #tem)  or aid='' 
 end

 exec SP 

Not sure why the answer above states making default value = NULL is incorrect but this works for me.不知道为什么上面的答案说明使默认值 = NULL 是不正确的,但这对我有用。

CREATE PROCEDURE SP
(
    @Param1 VARCHAR(10),
    @Param2 VARCHAR(10)=NULL
)

SELECT......
WHERE @Param1 = SOMETHING
AND (@Param2 = SOMETHING OR @Param2 IS NULL)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM