SQL在SELECT中使用变量

时间:2011-07-06 21:41:14

标签: sql sql-server sql-server-2008

我可以复制一行并在同一个表中更改单个字段的值,这样就完全正常了:

INSERT INTO myTable (foo,bar)
    SELECT foo,'new bar'
    FROM myTable
    WHERE rowIndex=5

但是我想用内联变量替换'new bar'。我试过这个无济于事:

DECLARE @Bar varchar(50) = 'new bar'
INSERT INTO myTable (foo,bar)
    SELECT foo,@Bar
    FROM myTable
    WHERE rowIndex=5

我刚刚抛出一个错误,指出@Bar是一个无效的列。

有办法做到这一点吗?

4 个答案:

答案 0 :(得分:3)

我在笔记本电脑上运行此代码 - SQL Server 2K8 v10.0.1600

CREATE TABLE #MyTable (
  rowIndex Int IDENTITY(1, 1),
  foo VarChar(10),
  bar VarChar(50)
);

DECLARE @Bar VarChar(50) = 'new bar';
INSERT INTO #MyTable (foo, bar)
    SELECT foo, @Bar
    FROM #MyTable
    WHERE rowIndex = 5;

DROP TABLE #MyTable;

如果作为单个批次执行它并且(与临时表除外)与您的相同,它可以正常工作。

答案 1 :(得分:3)

万一你认为Yuck的答案在临时表中存在问题,这是一个非临时表

CREATE TABLE 
         myTable 
  (foo varchar (50),
   bar varchar(50) ,
   rowIndex int identity)

SET identity_INSERT MyTable on 
INSERT INTO myTable  (foo, bar, rowIndex ) values ('foo','bar', 50)
SET identity_INSERT MyTable oFF

DECLARE @Bar varchar(50) = 'new bar'
INSERT INTO myTable (foo,bar)
    SELECT foo,@Bar
    FROM myTable
    WHERE rowIndex=50

    select foo, bar , rowIndex
    from myTable
    Drop table mytable

结果

foo bar     rowIndex
--- ------- --------
foo bar     50
foo new bar 51

这也可以在c#中使用SQLDataClient

using(SqlConnection cnn = new SqlConnection("Data Source=yoursever;Initial  Catalog=yourDB;Integrated Security=SSPI;"))
{ 
    cnn.Open();
    SqlCommand cmd = cnn.CreateCommand();

    cmd.CommandText = @"DECLARE @Bar varchar(50) = 'new bar' 
                        INSERT INTO myTable (foo,bar)   
                        SELECT foo,
                             @Bar    
                         FROM 
                           myTable    
                         WHERE rowIndex=50";
    cmd.ExecuteNonQuery();
}

答案 2 :(得分:1)

而不是:

DECLARE @Bar VarChar(50) = 'new bar' 
你能试试吗? :

DECLARE @Bar VarChar(50) 
SET @Bar = 'new bar' 

答案 3 :(得分:0)

你应该使用Stored Procedures

这样的东西

对不起,这可能是我的经历,但我以前从未见过插入SELECT?

MYSQL示例

DELIMITER //
    CREATE PROCEDURE InsertInto_myTable(
        IN Bar              VARCHAR(11)
    )
    BEGIN
        INSERT INTO `myTable` (foo,bar) SELECT `foo`,@Bar FROM `myTable` WHERE rowIndex = 5;
    END //
DELIMITER ;

完成此操作后,您只需致电CALL InsertInto_myTable('new bar')

MSSQL示例

CREATE PROCEDURE InsertInto_myTable(
    Bar varchar(50)
)
BEGIN
    INSERT INTO myTable (foo,bar) 
    SELECT foo,@Bar
    FROM myTable
    WHERE rowIndex=5;
END

使用 EXECUTE InsertInto_myTable('new bar');