如何根据列单元格值为变量分配不同的值

时间:2014-12-02 01:09:32

标签: sql

我需要遍历所有行并执行以下操作:

If the Date_Deleted is null then SET @Form = '01' else @Form = '02'

目前仅返回Form = 01。

谢谢!

SELECT @CHECKDATE = [DATE_DELETED] 
FROM Executive__Vehicles
WHERE (STATE = 'NC') 

IF ( @CHECKDATE is null )
    BEGIN
        SET @FORM = '01'        
    END
ELSE  
    BEGIN
        SET @FORM = '02'   
    END 

1 个答案:

答案 0 :(得分:0)

您需要将Executive_vehicles的所有结果加载到临时表中,然后逐个循环遍历它们。

CREATE TABLE #tempTable1(iID int identity(1,1),date_deleted datetime)
INSERT INTO #tempTable1
select [DATE_DELETED]
FROM Executive__Vehicles WHERE (STATE = 'NC')

DECLARE @countROws int 
DECLARE @CHECKDATE datetime
DECLARE @topRow INT
SET @countRows =(SELECT COUNT(*) FROM #tempTable1)
WHILE @countRows>0
BEGIN
SET @topRow = (SELECT TOP 1 iID from #tempTable1)
SET @CHECKDATE = (SELECT TOP 1 date_deleted from #tempTable1)
 IF ( @CHECKDATE is null )
BEGIN SET @FORM = '01'
END

ELSE  
BEGIN
SET @FORM = '02'   
END 

DELETE FROM #tempTable1 where iID=@topRow
set @countRows = (SELECT count(*) FROM #tempTable1)
set @CHECKDATE  = NULL
END

编辑添加标识列,因为date_deleted对于多行可以是相同的,删除会删除所有行。