如何在SQL中具有varchar的过程中查找参数

时间:2019-04-28 06:57:18

标签: sql-server stored-procedures

我想在程序中识别我的参数(由我的应用程序发送)。

只要包含varchar或仅包含整数值,并且由于此write where子句

alter procedure x
    @NumStr as varchar(50)
as 
    Select * 
    From y
    Where ...

我想这样做,但是我不知道在where子句中怎么做:

(if @numstr contains Varchar then numstr = @Numstr
and if @numstr contains just Integer  then serial = @Numstr)

3 个答案:

答案 0 :(得分:0)

您可以使用TRY_PARSE。如果输入参数为varchar,它将返回NULL,因此您可以在IF ELSE块中进行处理。

因此过程将是:

ALTER PROCEDURE X
( @NumStr VARCHAR (50) )
AS
BEGIN

   DECLARE @InputValidator AS INT = NULL;
   SELECT @InputValidator = TRY_PARSE(@NumStr AS INT);

   IF (@InputValidator IS NULL)
   BEGIN
      SELECT * 
      FROM Y
      WHERE numstr = @Numstr
   END
  ELSE
   BEGIN
      SELECT * 
      FROM Y
      WHERE serial = @Numstr -- in case if you are recive any error change this line to " WHERE serial = CAST(@Numstr AS INT) "
  END
END

答案 1 :(得分:0)

您可以使用:

select a.name AS ParamName ,s.name AS TypeName
from sys.procedures p 
        join sys.all_parameters a on p.object_id=a.object_id
        join sys.systypes s on s.xtype=a.system_type_id
where p.name ='SpName'

但是我更喜欢使用@Arulkumar或使用@Larnu所说的2个参数

答案 2 :(得分:0)

有时此参数@NumStr具有字符串值,有时是整数 每当由于业务层而成为字符串时,它也需要另外一个非空列 ,所以我会得到:

do { 
    var res = try JSONDecoder().decode(Root.self, from:data)

    res.letters.append(["test3":[Test(priority: 6, description: "des")]])

    res.letters[0]["Test2"]?.append(Test(priority: 612, description: "des2"))

    let wer = try JSONEncoder().encode(res)

    let json = String(data: wer, encoding: .utf8)

    print(json)
}
catch {
    print(error)
}