2011-10-18 83 views
1

我想在SQL Server 2005中使用一個簡單的函數,它會產生一個錯誤。如何在SQL Server 2005的用戶定義函數中使用truncate table並插入表中?

CREATE FUNCTION [dbo].[fn_data_stat_cc_update] 
(
    @result char 
) 
RETURNS char(1) 
AS 
    BEGIN 
    truncate table stg_data_cancer_center; 

    INSERT INTO stg_data_cancer_center(
      mrn, pt_city, pt_state, pt_zip, pt_pri_dx, clinic, source 
    SELECT rtrim(ltrim(mrn)) as mrn, 
    pat_city, pat_state, zipcode, exact_icd9_code_pri_dx, 'clinic' = 
    case 
     when inst_id = 1 then 'CANRAD' 
     when inst_id = 2 then 'CANHAM' 
     else @result--'' 
    end, 'MOSAIQ' as Source 
    from stg_mosaiq_patient; 

    RETURN LTRIM(RTRIM(@result)) 
    END 

錯誤是:

Procedure fn_data_stat_cc_update, Line 18 
Invalid use of side-effecting or time-dependent operator in 'TRUNCATE TABLE' within a function. 
Procedure fn_data_stat_cc_update, Line 25 
Invalid use of side-effecting or time-dependent operator in 'INSERT' within a function. 

回答

3

你不能。

您需要使用存儲過程。不允許函數具有修改數據等副作用。

+0

謝謝你,馬丁。我將創建一個stor proc。 – pots06

相關問題