试图将SEQUENCE数字插入INSERT语句但有问题

时间:2018-03-05 14:42:22

标签: sql sql-server tsql

我正在尝试使用SQL Server 2014创建一个需要在INSERT语句中递增的序列值。我有一个变量,其中包含我试图插入临时表的最大数+ 1但是对于插入TEMP TABLE的每个记录,需要递增数字。在谷歌搜索这个问题后,我发现我需要创建一个DYNAMIC SQL语句才能使用变量值。但是,当我这样做时,我现在得到一个转换错误。

任何帮助/指示将不胜感激。谢谢。

这是我的代码:

public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor) {
    return CompletableFuture.supplyAsync(new SupplierMDC(supplier), executor);
}

private static class SupplierMDC<T> implements Supplier<T> {
    private final Supplier<T> delegate;
    private final Map<String, String> mdc;

    public SupplierMDC(Supplier<T> delegate) {
        this.delegate = delegate;
        this.mdc = MDC.getCopyOfContextMap();
    }

    @Override
    public T get() {
        MDC.setContextMap(mdc);
        return delegate.get();
    }
}

我得到的错误是:

DECLARE @id int;
DECLARE @sql NVARCHAR(MAX);
SET @id = (SELECT MAX(rowNum)+1 FROM dbo.Focus_Export_Econ_DisadvantagedHHS_Staging_TEST)
SET @sql = 'CREATE SEQUENCE dbo.ID_Sequence
    AS INT
    START WITH ' + @id + 
    'INCREMENT BY 1
    NO MAXVALUE'
EXEC @sql;
SELECT NEXT VALUE FOR @sql, T.*
INTO #TEMP_TEST  --DROP TABLE #TEMP_TEST 
FROM (SELECT h.SiteID, st.SchoolName, st.CEPSchool, st.StudentID, st.FName, st.LName, st.Grade, UPPER(LEFT(h.Status,1))+LOWER(SUBSTRING(h.Status,2,LEN(h.Status))) as Status, 
        (CASE
            WHEN UPPER(h.Status) = 'FREE' THEN '01'
            WHEN UPPER(h.Status) = 'REDUCED' THEN '02'
            WHEN UPPER(h.Status) = 'PAID' THEN '00'
        END) as EconomicDisadvantageCode, 
        (CASE 
            WHEN ltrim(h.AppType) = 'HS Survey' THEN 'HH' 
        END) as ApplicationTypeCode,
        'HouseHold Survey' as ApplicationType,
        st.ResAddr, st.City, st.ZipCode, st.State, st.Phone, 
        CONVERT(VARCHAR(10), CAST(h.Effective_Date as date), 101) as StatusEffectiveDate, h.End_Date, st.SchoolYear, 
        st.BirthDate, st.AppScanned, st.AppOnline, st.GracePeriodID,
        (CASE
            WHEN ISNUMERIC(h.APPID) = 1 THEN CONVERT(INT, h.APPID) ELSE NULL 
        END) as ApplicationID 
    FROM #TEMP_HHS_Historical_Records h
    INNER JOIN dbo.Focus_Export_Econ_DisadvantagedHHS_Staging_TEST st
    ON h.CustomerID = st.StudentID) as T;

2 个答案:

答案 0 :(得分:2)

我认为问题出在动态SQL中。您可以通过执行以下操作来解决此问题:

GET

我不确定SET @sql = 'CREATE SEQUENCE dbo.ID_Sequence AS INT START WITH ' + cast(@id as varchar(255) + ' INCREMENT BY 1 NO MAXVALUE' EXEC (@sql); 语句是否允许参数,但这比使用像这样的值来修改字符串更好。

答案 1 :(得分:1)

您需要将ID转换为nvarchar,如下所示:

DECLARE @id int;
DECLARE @sql NVARCHAR(MAX);
SET @id = (SELECT MAX(rowNum)+1 FROM dbo.Focus_Export_Econ_DisadvantagedHHS_Staging_TEST)
SET @sql = 'CREATE SEQUENCE dbo.ID_Sequence
    AS INT
    START WITH ' + cast(@id as nvarchar(100)) + 
    'INCREMENT BY 1
    NO MAXVALUE'
   exec sp_executesql @sql;

--TO GET THE VALUE INTO @ID
SELECT  @id = NEXT VALUE FOR dbo.ID_Sequence

您只需要创建一次序列。 您可以迭代并获取@id值。 希望它有所帮助!