tags:

views:

32

answers:

3

I have a (hopefully) quick SQL question that is driving me nuts and I have not been able to locate an answer anywhere.

I have the following SQL trigger:

DECLARE @ABCOwnerGroup varchar(30)
DECLARE @DEFOwnerGroup varchar(30)
SET @ABCOwnerGroup='GROUP ONE'
SET @DEFOwnerGroup='GROUP TWO'
etc..

--IF OWNERGROUP IS MISSING (Location NOT NULL)
    UPDATE wo
        SET wo.ownergroup='@'+SUBSTRING(wo.location,1,3)+'OwnerGroup'
    FROM dbo.workorder AS wo INNER JOIN inserted AS i ON wo.wonum=i.wonum
    WHERE wo.status<>'COMP'
        AND wo.historyflag=0
        AND wo.istask=0    
        AND wo.ownergroup IS NULL
        AND wo.location IS NOT NULL

For your information, the location codes are like 'ABC-12345' where ABC is essentially the site and 12345 is the building. So the SUBSTRING(wo.location,1,3) pulls the ABC part of the location so that it can fill in @ABCOwnerGroup

The issue is that it is inserting the value '@ABCOwnerGroup' instead of 'GROUP ONE'

Any and all help is greatly appreciated! Hopefully this is a minor error!

+2  A: 

You need to express your entire update as a string, and use Exec to execute it.

klausbyskov
+3  A: 

You'll need to use an EXECUTE to exec dynamic SQL

EXEC('UPDATE wo SET wo.ownergroup=@'+SUBSTRING(wo.location,1,3)+'OwnerGroup FROM dbo.workorder AS wo INNER JOIN inserted AS i ON wo.wonum=i.wonum
WHERE wo.status<>''COMP''
    AND wo.historyflag=0
    AND wo.istask=0    
    AND wo.ownergroup IS NULL
    AND wo.location IS NOT NULL')
Matt Fellows
-1 for not using CASE. poor thinking.
gbn
Dynamic SQl in a trigger makes me shudder with horror.
HLGEM
It is my understanding that Dynamic SQL does not have access to the INSERTED table. Is this correct? If so, I would have to create parameters for the Dynamic SQL and pass the INSERTED table. This seems like a nightmare!
D.R.
+4  A: 

Alternatively you can get the same result without dynamic sql with the following:

--IF OWNERGROUP IS MISSING (Location NOT NULL)
    UPDATE wo
        SET wo.ownergroup = CASE SUBSTRING(wo.location, 1, 3)
                                WHEN 'ABC' THEN 'GROUP ONE'
                                WHEN 'DEF' THEN 'GROUP TWO'
                            END
    FROM dbo.workorder AS wo
    INNER JOIN inserted AS i ON wo.wonum = i.wonum
    WHERE wo.status <> 'COMP'
        AND wo.historyflag = 0
        AND wo.istask = 0
        AND wo.ownergroup IS NULL
        AND wo.location IS NOT NULL
ulty4life
I assume I could also use: "WHEN 'ABC' THEN @ABCOwnerGroup" etc Correct?
D.R.
I used this method and it is working beautifully
D.R.
Yes, you can use a variable in the THEN part of the case statement.You might also want to consider a calculated column as part of the table definition: http://msdn.microsoft.com/en-us/library/ms191250.aspx
ulty4life