如果SQL Server

时间:2016-05-19 18:47:11

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

我有这个示例数据的表test

id   name   user_id
-------------------
1     sd       0
3     ds       0
4     ss       0

... etc

现在我想更新虚拟值op user_id列以90000000001(12位数)开头,如果用户ID为零。我们如何实现这一目标?

我从未遇到过这个。

3 个答案:

答案 0 :(得分:0)

您可以使用变量执行此操作:

DECLARE @user_id bigint
SET @user_id = 90000000000
UPDATE test
SET @user_id= user_id = @user_id + 1

答案 1 :(得分:0)

我认为你正在寻找这个:

Create Table Test (ID Int, Name Varchar(8000), User_Id BigInt)
Insert Test Values (1, 'Joe', 1)
Insert Test Values (2, 'John', 800)
Insert Test Values (3, 'Jerry', 0)
Insert Test Values (4, 'Jane', 100)
Insert Test Values (5, 'Jim', 0)
Insert Test Values (6, 'Jamie', 8997)

Update T Set T.User_ID = Q.Dummy
    From Test T
    Join (Select ID, Row_Number() Over (Order By ID) + 9000000000 Dummy From Test Where User_Id = 0) Q On Q.ID = T.ID

Select * From Test

答案 2 :(得分:0)

假设我正确理解了您的问题,那么以下内容应该可以达到您想要的效果:

    UPDATE  test
    SET     [user_id] = CAST(NewIDs.new_user_id AS BIGINT)
    FROM    test
    INNER JOIN  (
                    SELECT  [id]
                            ,[name]
                            ,'9' + RIGHT('0000000000'+ CAST(ROW_NUMBER() OVER (ORDER BY [id]) AS VARCHAR(11)),11)  AS [new_user_id]
                    FROM    test ZeroID  
                    WHERE   [user_id] = 0
                ) NewIDs ON NewIDs.id = test.id