表值参数到存储过程是否具有默认值

时间:2015-10-01 18:42:04

标签: sql sql-server

假设我有两列用户定义表类型

from bs4 import BeautifulSoup
import requests

response = requests.get('http://vpnbook.com/freevpn')
soup = BeautifulSoup(response.text, 'html.parser')
pricing = soup.find(id = 'pricing')
first_column = pricing.find('div', {'class': 'one-third'})
for li in first_column.find('ul', {'class': 'disc'}):
    if 'password' in str(li).lower():
        password = li.find('strong').text
print(password)

进一步假设我有将表类型传递给

的存储过程
CREATE TYPE [Schema].[Type] AS TABLE (
    [Name]         NVARCHAR (100) NULL
    [Value]         int NULL
);

我可以将@TVP的值默认为

CREATE PROCEDURE [Schema].[sp_SomeProcedure]
@TVP [Type] READONLY
AS
SELECT 
[Name]
,1 + [Value]
FROM
@TVP

2 个答案:

答案 0 :(得分:4)

调用程序时,您可以使用TVP的'DEFAULT'关键字。这将传递一个类型的空表。

示例 - 如果TVP是传递给过程的第二个参数:

    Exec myProcedure (intParam, DEFAULT) 

答案 1 :(得分:3)

SQL Server不允许将TVP作为可选参数,但为其设置某种默认值,如果您的过程中有TVP,则需要在运行时传递TVP。

但是有一种解决方法,在你的程序中添加另一个参数来决定你程序中TVP的行为。

请注意,在任何情况下,您都需要在运行时将TVP传递给您的程序。

CREATE PROCEDURE [Schema].[sp_SomeProcedure]
   @TVP_Default BIT = 1 
  ,@TVP [dbo].[Test_Type] READONLY
AS
BEGIN
    DECLARE @tempTable TABLE (
                            [Name]  NVARCHAR(100) NULL
                           ,[Value] int NULL
                           );

-- If @TVP_Default = 1 default values will be populated 
-- else values passed to TVP will be used    
IF (@TVP_Default = 1)
  BEGIN 
    INSERT INTO @tempTable([Name] , [Value])
    SELECT 'John' , 1
  END
ELSE
  BEGIN 
    INSERT INTO @tempTable([Name] , [Value])
    SELECT   [Name]
          ,1 + [Value]
    FROM @TVP
  END

  /*   
        rest of the code

       use @tempTable instead of the TVP in rest of the code
  */

END