动态选择语句

时间:2017-01-21 00:36:32

标签: sql-server dynamic

  
    

我有以下INSERT语句(代码1)我需要更改它,因为它将从另一个数据库获取数据,因此需要采用形式OF(代码2)     那可能吗?

  
git reset --hard

1 个答案:

答案 0 :(得分:0)

system view's

之前添加数据库名称
INSERT INTO @V_ColumnDefinition
            (FieldValue)--add primary key constraint to definition table
SELECT Char (10)
       + CASE
           WHEN A1.NAME IS NOT NULL THEN ' CONSTRAINT  [' + A1.NAME + ' ] '
           ELSE ''
         END
       + CASE
           WHEN A1.NAME IS NOT NULL
                AND A2.type_desc = 'CLUSTERED'
                AND A1.NAME = A2.NAME THEN 'PRIMARY KEY CLUSTERED'
           ELSE 'PRIMARY KEY NONCLUSTERED'
         END
       + '(' + Char(10) + '['
       + CASE
           WHEN A1.NAME = A3.CONSTRAINT_NAME THEN COLUMN_NAME
         END
       + ' ]' + ')'
FROM   dataname.SYS.OBJECTS A1
       LEFT JOIN dataname.SYS.INDEXES A2
              ON A1.object_id = A2.Object_id
       LEFT JOIN dataname.INFORMATION_SCHEMA.KEY_COLUMN_USAGE A3
              ON A1.NAME = A3.CONSTRAINT_NAME
WHERE  A1.TYPE = 'PK'
       AND parent_object_id = Object_id (@P_TableName) 

如果数据库名称未知,那么。

DECLARE @sql         VARCHAR(max)='',
        @dataname    SYSNAME = 'databasename',
        @P_TableName SYSNAME = 'tablename'

SET @sql = 'INSERT INTO #V_ColumnDefinition
            (FieldValue)--add primary key constraint to definition table
SELECT Char (10)
       + CASE
           WHEN A1.NAME IS NOT NULL THEN '' CONSTRAINT  ['' + A1.NAME + '' ] ''
           ELSE ''''
         END
       + CASE
           WHEN A1.NAME IS NOT NULL
                AND A2.type_desc = ''CLUSTERED''
                AND A1.NAME = A2.NAME THEN ''PRIMARY KEY CLUSTERED''
           ELSE ''PRIMARY KEY NONCLUSTERED''
         END
       + ''('' + Char(10) + ''[''
       + CASE
           WHEN A1.NAME = A3.CONSTRAINT_NAME THEN COLUMN_NAME
         END
       + '' ]'' + '')''
FROM   ' + Quotename(@dataname)
           + '.SYS.OBJECTS A1
       LEFT JOIN ' + Quotename(@dataname)
           + '.SYS.INDEXES A2
              ON A1.object_id = A2.Object_id
       LEFT JOIN ' + Quotename(@dataname)
           + '.INFORMATION_SCHEMA.KEY_COLUMN_USAGE A3
              ON A1.NAME = A3.CONSTRAINT_NAME
WHERE  A1.TYPE = ''PK''
       AND parent_object_id = Object_id ('''
           + @P_TableName + ''') 
'

PRINT @sql

EXEC(@sql) 

将变量临时表更改为#temp表以访问内部动态查询。如果你想使用变量临时表,那么下面的评论将更新我的答案。