我可以在参数后面创建表名和列名吗?

时间:2012-02-18 02:26:20

标签: sql-server tsql

我只想在我的函数后面创建一个表和列,返回nvarchar数据类型,我该如何创建?请参阅下面的代码:

IF @mode = 3 
        CREATE TABLE TMP(
            TMPID INT,
            [NAMES] NVARCHAR(50),
            [dbo.GetMonthNameOfDate(@date)] MONEY,
            [dbo.GetMonthNameOfDate(DATEADD(M,1,@date))] MONEY,
            [dbo.GetMonthNameOfDate(DATEADD(M,2,@date))] MONEY
        )
    ELSE
        CREATE TABLE TMP(
            TMPID INT,
            [dbo.GetMonthNameOfDate(@date)] MONEY,
            [dbo.GetMonthNameOfDate(DATEADD(M,1,@date))] MONEY,
            [dbo.GetMonthNameOfDate(DATEADD(M,2,@date))] MONEY,
            [dbo.GetMonthNameOfDate(DATEADD(M,3,@date))] MONEY,
            [dbo.GetMonthNameOfDate(DATEADD(M,4,@date))] MONEY,
            [dbo.GetMonthNameOfDate(DATEADD(M,5,@date))] MONEY,
            [dbo.GetMonthNameOfDate(DATEADD(M,6,@date))] MONEY,
            [dbo.GetMonthNameOfDate(DATEADD(M,7,@date))] MONEY,
            [dbo.GetMonthNameOfDate(DATEADD(M,8,@date))] MONEY,
            [dbo.GetMonthNameOfDate(DATEADD(M,9,@date))] MONEY,
            [dbo.GetMonthNameOfDate(DATEADD(M,10,@date))] MONEY,
            [dbo.GetMonthNameOfDate(DATEADD(M,11,@date))] MONEY
        )

GetMonthNameOfDate是一个返回一年中月份名称的函数。

1 个答案:

答案 0 :(得分:0)

使用动态sql。

DECLARE @sql varchar(2000)
IF @mode = 3 
    set @sql = '
    CREATE TABLE TMP(
        TMPID INT,
        [NAMES] NVARCHAR(50),
        [' + dbo.GetMonthNameOfDate(@date) + '] MONEY,
        [' + dbo.GetMonthNameOfDate(DATEADD(M,1,@date))'] MONEY,
        [' + dbo.GetMonthNameOfDate(DATEADD(M,2,@date))'] MONEY
    )'
ELSE
    set @sql = '
    CREATE TABLE TMP(
        TMPID INT,
        [' + dbo.GetMonthNameOfDate(@date)+ '] MONEY,
        [' + dbo.GetMonthNameOfDate(DATEADD(M,1,@date))+ '] MONEY,
        [' + dbo.GetMonthNameOfDate(DATEADD(M,2,@date))+ '] MONEY,
        [' + dbo.GetMonthNameOfDate(DATEADD(M,3,@date))+ '] MONEY,
        [' + dbo.GetMonthNameOfDate(DATEADD(M,4,@date))+ '] MONEY,
        [' + dbo.GetMonthNameOfDate(DATEADD(M,5,@date))+ '] MONEY,
        [' + dbo.GetMonthNameOfDate(DATEADD(M,6,@date))+ '] MONEY,
        [' + dbo.GetMonthNameOfDate(DATEADD(M,7,@date))+ '] MONEY,
        [' + dbo.GetMonthNameOfDate(DATEADD(M,8,@date))+ '] MONEY,
        [' + dbo.GetMonthNameOfDate(DATEADD(M,9,@date))+ '] MONEY,
        [' + dbo.GetMonthNameOfDate(DATEADD(M,10,@date))+ '] MONEY,
        [' + dbo.GetMonthNameOfDate(DATEADD(M,11,@date))+ '] MONEY
    )'

exec sp_executesql @sql