代码之家  ›  专栏  ›  技术社区  ›  Steve Cooper

SQL变量;当参数不存在时声明

  •  1
  • Steve Cooper  · 技术社区  · 14 年前

    我正在编写一个SQL脚本,我想使用ManagementStudio来开发查询,并使用C程序在生产环境中运行它。

    我的查询包含参数,就像这样;

    SELECT * FROM TABLE
    WHERE id = @id
    

    我可以输入一个值 @id 在C程序中,这很好地工作。但是,我还想声明在ManagementStudio中测试的默认值。所以我真的想写一些像这样的伪代码;

    if not declared @id
      declare @id int
      set @id=43
    end if
    
    SELECT * FROM TABLE   
    WHERE id = @id
    

    是否有任何方法检查变量名是否已被占用?

    2 回复  |  直到 14 年前
        1
  •  4
  •   AdaTheDev    14 年前

    你不能做你想要的。我建议:

    1)将脚本包装为存储过程,并为参数提供默认值
    2)在脚本顶部包含一个注释块,在SSMS中运行时可以取消注释:

    /*
    -- Default variables for testing
    DECLARE @Id INTEGER
    SET @Id = 43
    */
    SELECT * FROM Table WHERE id = @Id
    
        2
  •  1
  •   Steve Cooper    14 年前

    我已经设法通过在脚本中标记出默认变量来取得一些进展,就像这样;

    /** DEFAULTS **/
    
    declare @id int
    set @id = 43
    
    /** END DEFAULTS **/
    

    然后在我的C程序中预处理脚本,就像这样;

    script = RemoveBlock(script, "DEFAULTS");
    

    像这样实现功能;

    public static string RemoveBlock(string script, string blockName)
    {
        if (script == null) { return null; }
    
        var startTag = string.Format("/** {0} **/", blockName);
        var endTag = string.Format("/** END {0} **/", blockName);
    
        var startTagIdx = script.IndexOf(startTag);
        if (startTagIdx == -1) { return script; }
    
        var endTagIdx = script.IndexOf(endTag, startTagIdx + startTag.Length);
        if (endTagIdx == -1) { return script; }
    
        var endOfEndTag = endTagIdx + endTag.Length;
    
        var beforeBlock = script.Substring(0, startTagIdx);
        var afterBlock = script.Substring(endOfEndTag);
    
        return beforeBlock + afterBlock;
    }
    

    所以C程序运行的版本没有变量,但是有参数。