SQL Server stored procedure parameters

前端 未结 5 1550
[愿得一人]
[愿得一人] 2020-12-08 07:09

I am developing a framework, where in I am a calling stored procedure with dynamically created parameters. I am building parameter collection at the runtime.

The pr

5条回答
  •  无人及你
    2020-12-08 07:39

    I'm going on a bit of an assumption here, but I'm assuming the logic inside the procedure gets split up via task. And you cant have nullable parameters as @Yuck suggested because of the dynamics of the parameters?

    So going by my assumption

    If TaskName = "Path1" Then Something

    If TaskName = "Path2" Then Something Else

    My initial thought is, if you have separate functions with business-logic you need to create, and you can determine that you have say 5-10 different scenarios, rather write individual stored procedures as needed, instead of trying one huge one solution fits all approach. Might get a bit messy to maintain.

    But if you must...

    Why not try dynamic SQL, as suggested by @E.J Brennan (Forgive me, i haven't touched SQL in a while so my syntax might be rusty) That being said i don't know if its the best approach, but could this could possibly meet your needs?

    CREATE PROCEDURE GetTaskEvents
        @TaskName varchar(50)
        @Values varchar(200)
    AS
    BEGIN
      DECLARE @SQL VARCHAR(MAX)
    
      IF @TaskName = 'Something'
      BEGIN
        @SQL = 'INSERT INTO.....' + CHAR(13)
        @SQL += @Values + CHAR(13) 
      END
    
      IF @TaskName = 'Something Else'
      BEGIN
        @SQL = 'DELETE SOMETHING WHERE' + CHAR(13)
        @SQL += @Values + CHAR(13) 
      END
    
      PRINT(@SQL)
      EXEC(@SQL)    
    END
    

    (The CHAR(13) adds a new line.. an old habbit i picked up somewhere, used to help debugging/reading dynamic procedures when running SQL profiler.)

提交回复
热议问题