所有行都在SQL Server中进行更新

时间:2016-07-05 12:47:48

标签: sql sql-server tsql

我正在尝试更新单行,但发现所有行都在进行更新。

今天早上被困住了。我不想使用数据表。

CREATE PROCEDURE [dbo].[spUserProfile]
    @FirstName nvarchar(50),
    @MiddleName nvarchar(50),
    @LastName nvarchar(50),
    @Mobile nvarchar(50),
    @Aadhar nvarchar(50),   
    @PAN nvarchar(50),
    @Address text,
    @CityID int,
    @PinCode int,
    @StateID int,
    @CountryID int
AS
BEGIN
    UPDATE tblUserProfiles  
    SET FirstName = @FirstName, 
        MiddleName = @MiddleName, 
        LastName = @LastName, 
        Mobile = @Mobile, Aadhar = @Aadhar, 
        PAN = @PAN, Address = @Address, 
        CityID = @CityID, PinCode = @PinCode, 
        StateID = @StateID, CountryID = @CountryID
    WHERE
        UserID = UserId 
END
从另一个表触发

UserID以将其存储在此表中。所以我不需要再提供它

请给我一个解决方案并错误地告诉我

4 个答案:

答案 0 :(得分:5)

  

WHERE UserID = UserID

使用此WHERE子句,您的查询将更新UserID的列值等于其自身的每一行。这是每一行。 (编辑:除非,如下所示,如果您有UserID为NULL的行)

要让它只更新一行,请将UserID设置为特定值。

实施例: WHERE UserID = '10'

要让它更新一组行,请使用子查询或WHERE IN,如下所示: WHERE UserID IN (1,2,3,4,etc)

本网站上的参考页面可以帮助您:
http://www.w3schools.com/sql/sql_where.asp
http://www.w3resource.com/sql/subqueries/understanding-sql-subqueries.php

答案 1 :(得分:1)

UPDATE将更新符合条件的所有行。缺少条件时,SQL会将UPDATE视为更新所有内容的请求。

看起来您正在尝试更新由其用户ID标识的用户的记录,因此查询应更改如下:

UPDATE tblUserProfiles  
SET
    FirstName = @FirstName
,   MiddleName = @MiddleName
,   LastName = @LastName
,   Mobile = @Mobile
,   Aadhar = @Aadhar
,   PAN = @PAN
,   Address = @Address
,   CityID = @CityID
,   PinCode = @PinCode
,   StateID = @StateID
,   CountryID = @CountryID
WHERE UserID = @UserId -- add a WHERE clause

答案 2 :(得分:0)

create proc [dbo].[spUserProfile]
@FirstName nvarchar(50),
@MiddleName nvarchar(50),
@LastName nvarchar(50),
@Mobile nvarchar(50),
@Aadhar nvarchar(50),   
@PAN nvarchar(50),
@Address text,
@CityID int,
@PinCode int,
@StateID int,
@CountryID int,
@UserId Int -- Added the missing argument

AS
Begin

    update tblUserProfiles  
    Set FirstName = @FirstName, MiddleName = @MiddleName, LastName = @LastName, 
        Mobile = @Mobile, Aadhar = @Aadhar, 
        PAN = @PAN, Address = @Address, CityID = @CityID,               
        PinCode = @PinCode, StateID = @StateID, CountryID = @CountryID,
        Where UserID = @UserId  -- Added the where clause

End 

答案 3 :(得分:0)

UPDATE的SQL语法如下:

UPDATE tablename 
SET column1 = value1, .... columnN = valueN
WHERE (condition)

您可以在此处找到相同内容:http://www.w3schools.com/sql/sql_update.asp

将上述语法与您的代码进行比较,在where子句开始之前的额外逗号(,)可能是您的代码没有遇到where子句的原因。

TRY:

UPDATE tblUserProfiles  
SET FirstName = @FirstName, 
    MiddleName = @MiddleName, 
    LastName = @LastName, 
    Mobile = @Mobile, Aadhar = @Aadhar, 
    PAN = @PAN, Address = @Address, CityID = @CityID,               
    PinCode = @PinCode, StateID = @StateID, CountryID = @CountryID
WHERE 
    UserID = UserId