sqlserver 針對預處理sql傳入引數的處理方式

weixin_34321977發表於2017-03-21


在編寫sql中,經常需要對sql進行預處理,動態拼接字串,那麼要獲取在這預處理之後返回的的某個值並且賦值,傳入引數的語法

  1. USE [OA]
  2. GO
  3. /****** Object: StoredProcedure [dbo].[usp_oa_UserMessageProve_Update] Script Date: 12/02/2014 10:45:19 ******/
  4. SET ANSI_NULLS ON
  5. GO
  6. SET QUOTED_IDENTIFIER ON
  7. GO
  8. /*
  9. 功能:更新使用者證明資料,更新使用者證明狀態
  10. 2014.10.28 16:14 am
  11. */
  12. ALTER PROC [dbo].[usp_oa_UserMessageProve_Update]
  13. @msgid VARCHAR(10)
  14. ,@userid VARCHAR(10)
  15. ,@state VARCHAR(10)
  16. ,@remark VARCHAR(200)
  17. ,@filepath VARCHAR(200)
  18. AS
  19. begin
  20. DECLARE
  21. @tablename VARCHAR(100)
  22. ,@provered INT
  23. ,@sqlstr NVARCHAR(1000)
  24. ,@provepath VARCHAR(1000)
  25. ,@NOT_PROVE INT --未證明
  26. ,@CANNOT_PROVE INT --無法完成
  27. ,@HAS_PROVE INT --已證明
  28. --無法證明更新
  29. SELECT @NOT_PROVE=56,@CANNOT_PROVE=58,@HAS_PROVE=57
  30. select @tablename=tablename from ADM_F_GETUSERREADTABLE (@userid)
  31. IF @state = '1' -- state =1 執行無法證明操作
  32. BEGIN
  33. SET @sqlstr = 'update '+@tablename+' set proveremark='''+@remark+''',provered='+CAST(@CANNOT_PROVE AS VARCHAR(10))
  34. + ' where UserID='+@userid + ' and MessageID='+@msgid
  35. EXEC(@sqlstr)
  36. END
  37. ELSE IF @state = '2' -- state = 2 執行 按鈕證明操作
  38. BEGIN
  39. SET @sqlstr = 'update '+@tablename+' set provered='+CAST(@HAS_PROVE AS VARCHAR(10))
  40. + ' where UserID='+@userid + ' and MessageID='+@msgid
  41. EXEC(@sqlstr)
  42. END
  43. ELSE IF @state = '3' -- state = 3 執行 檔案路徑更新操作
  44. BEGIN
  45. SET @sqlstr = 'update '+@tablename+' set provered='+CAST(@HAS_PROVE AS VARCHAR(10))+',provepath = isnull(provepath,'''')+ '''+@filepath
  46. +','' where UserID='+@userid + ' and MessageID='+@msgid
  47. EXEC(@sqlstr)
  48. END
  49. ELSE IF @state = '4' -- state = 4 執行檔案刪除更新操作
  50. BEGIN
  51. SET @sqlstr = 'select @provepath=provepath from '+@tablename+' where UserID='+@userid + ' and MessageID='+@msgid
  52. EXEC sp_executesql @sqlstr,
  53. N'@provepath VARCHAR(1000) output',
  54. @provepath OUTPUT
  55. SET @provepath= REPLACE(@provepath,@filepath+',','')
  56. SET @sqlstr = 'update '+@tablename+' set provepath = '''+@provepath+''''
  57. IF @provepath = ''
  58. BEGIN
  59. SET @sqlstr +=',provered='+CAST(@NOT_PROVE AS VARCHAR(10))
  60. END
  61. SET @sqlstr +=' where UserID='+@userid + ' and MessageID='+@msgid
  62. PRINT @sqlstr
  63. EXEC(@sqlstr)
  64. END
  65. END

相關文章