没有SELECT语句的WHERE?

时间:2014-07-07 09:15:44

标签: sql sql-server

我正在尝试运行以下代码将一些数据插入到我的表中。

在没有WHERE语句的情况下工作正常,但是当我尝试仅插入“语音呼叫”值时,它会在语法上出错。我认为这是因为使用WHERE我必须有一个SELECT语句,但我不确定SQL需要什么样的

Dim strSql As String = 
"INSERT INTO [" + FileNameOnly + "] (Account,[From],[To],Country,[Description],ConnectTime,ChargedTime,ChargedTimeSecs,ChargedAmount,ServiceName,ChargedQuantity,ServiceUnit) 
VALUES(@Account,@From,@To,@Country,@Description,@ConnectTime,@ChargedTime,@ChargedTimeSecs,@ChargedAmount,@ServiceName,@ChargedQuantity,@ServiceUnit) 
WHERE [ServiceName] = 'Voice Calls' "

非常感谢任何帮助。

谢谢,

2 个答案:

答案 0 :(得分:8)

您无法执行INSERT INTO... VALUES ... WHERE

您可以执行INSERT INTO... VALUES

INSERT INTO... SELECT ... WHERE

所以

INSERT INTO TARGETTABLE 
            (FIELDA, 
             FIELDB, 
             FIELDC, 
             FIELDD) 
SELECT 'A', --some "constant" value
       'B', --some "constant" value
       'C', --some "constant" value
       SOMEFIELDSFROMYOURTABLE --a field of YOURTABLE
FROM   YOURTABLE 
WHERE  SOMECONDITION 

但您的查询可能更新而不是插入?

UPDATE YOURTABLE 
SET    FIELDA = 'a', 
       FIELDB = 'b', 
       FIELDC = 'c', 
       FIELDD = 'd' 
WHERE  SERVICENAME = 'Voice Calls' 

答案 1 :(得分:0)

试试这个:

Dim strSql As String = 
"INSERT INTO [" + FileNameOnly + "] (Account,[From],[To],Country,[Description],ConnectTime,ChargedTime,ChargedTimeSecs,ChargedAmount,ServiceName,ChargedQuantity,ServiceUnit) 
SELECT *
From (Select @Account as [Account], @From as [From], ... ,@ServiceName as ServiceName, ...)z
WHERE z.[ServiceName] = 'Voice Calls' "