Using dynamic SQL to specify a column name by adding a variable to simple sql query

前端 未结 2 958
天涯浪人
天涯浪人 2020-12-06 15:02

sql 2005/ sql 2008

Declare @temp nvarchar(1000)

set @temp = \'ABC\'


select col1,col2 from tableA

Along with select query, how to add a v

相关标签:
2条回答
  • 2020-12-06 15:28

    If you are trying to specify the column name dynamically, you could take a look at executing dynamic sql. However, you should make sure to read about the dangers of this approach first:

    http://www.sommarskog.se/dynamic_sql.html

    From that page, there is a sample that shows dynamically specifying the table name -- you could change it so it dynamically specifies the column name instead:

    CREATE PROCEDURE general_select @tblname nvarchar(128),
                                    @key     varchar(10),
                                    @debug   bit = 0 AS
    DECLARE @sql nvarchar(4000)
    SET @sql = 'SELECT col1, col2, col3
                FROM dbo.' + quotename(@tblname) + '
                WHERE keycol = @key'
    IF @debug = 1 PRINT @sql
    EXEC sp_executesql @sql, N'@key varchar(10)', @key = @key
    

    So for example if you had a table 'MyTable' with columns named 'x', 'y', and 'z', it might look like:

    DECLARE @columnName nvarchar(128)
    DECLARE @sql nvarchar(4000)
    set @columnName = 'z'
    
    SET @sql = 'SELECT x, y, ' + @columnName + ' from MyTable'
    EXEC sp_executesql @sql, N'@columnName varchar(128)', @columnName = @columnName
    
    0 讨论(0)
  • 2020-12-06 15:33

    Something like this:

    select col1,col2 from tableA WHERE col1 = @temp
    

    Or this:

    select col1,col2,@temp as col3 from tableA WHERE col1 = @temp
    

    Or this:

    select col1,col2,@temp as col3 from tableA
    

    Or if @temp is a column name, then maybe you're looking for a dynamic query?

     SET @temp = 'select col1,col2, ' + @temp + ' as col3 from tableA'
     EXEC sp_executesql @temp
    

    ...

    0 讨论(0)
提交回复
热议问题