【发布时间】:2015-08-25 10:18:34
【问题描述】:
我有一个这样的存储过程:
create procedure [dbo].[InsertInput]
(@ResourceTag int, @Element varchar(50), @PeriodID int, @BackPay varchar(50), @InputValue decimal(18,5), @UserID varchar(50), @Source varchar(50), @InputDate datetime, @SourceID int, @Comments varchar(200), @ProcessID int, @TableCode int, @ScopeID int = NULL Output)
as
begin
INSERT INTO
[dbo].[Input]
([Resource Tag] ,[Element] ,[Period ID] ,[Back Pay], [Input Value], [User ID], [Source], [Input Date], [Source ID], [Comments], [Process ID])
Values(@ResourceTag, @Element, @PeriodID, @BackPay, @InputValue, @UserID, @Source, @InputDate, @SourceID, @Comments, @ProcessID)
set @ScopeID = (Select Scope_Identity())
end
现在我添加了参数@TableCode,根据这个值,上面的插入语句应该去不同的表。 例如, 如果@TableCode = 0,则插入 INTO [dbo].[Input]... 如果@TableCode = 1,则插入 INTO [dbo].[Input1]...
所以我尝试添加一个像这样 sn-p 的 CASE 语句:
INSERT INTO
CASE WHEN @TableCode = 0 THEN
[dbo].[Input]
([Resource Tag] ,[Element] ,[Period ID] ,[Back Pay], [Input Value], [User ID], [Source], [Input Date], [Source ID], [Comments], [Process ID])
Values(@ResourceTag, @Element, @PeriodID, @BackPay, @InputValue, @UserID, @Source, @InputDate, @SourceID, @Comments, @ProcessID)
set @ScopeID = (Select Scope_Identity())
但我刚刚收到类似于“'CASE' 附近的语法不正确”的错误。
在this 页面上,我没有看到将 CASE 与 INSERT 一起使用的示例,所以也许不可能?
我应该使用多个 if 语句吗? 如:
IF @TableCode = 0
Begin
INSERT INTO [dbo].[Input]
([Resource Tag] ,[Element] ,[Period ID] ,[Back Pay], [Input Value], [User ID], [Source], [Input Date], [Source ID], [Comments], [Process ID])
Values(@ResourceTag, @Element, @PeriodID, @BackPay, @InputValue, @UserID, @Source, @InputDate, @SourceID, @Comments, @ProcessID)
set @ScopeID = (Select Scope_Identity())
end
If @TableCode = 1...
【问题讨论】:
-
问题是什么?
-
不,你不能。您不能像这样将 case 语句与 insert 语句一起使用。如果你想使用你提到的 case 语句,那么你必须将你的 sql 语句转换为动态查询。
-
你应该看看这篇文章。如果你不稍微改变它,你就会面临一个非常具有挑战性的性能问题。 sqlinthewild.co.za/index.php/2009/09/15/…
标签: sql-server