简体   繁体   中英

combining a multiple queries into a single query (in SQL Server, with variables?)

I'd like to apply the following query to two other circ_slip values ('payment' and 'refund') for a large number of locations.

delete from circ_slip_field 
where location = 'NEW LOCATION' and circ_slip = 'waive'
go
declare @copy_loc varchar(7), @new_loc varchar(7) 
select @copy_loc = 'OLD LOCATION' 
select @new_loc = 'NEW LOCATION'
insert circ_slip_field
       (circ_slip,location,section,ord,circ_slip_field_type,label,field_column,
        append_to_prev,justify,max_field_len,min_field_len,data_mask)
select  circ_slip,@new_loc,section,ord,circ_slip_field_type,label,field_column,
        append_to_prev,justify,max_field_len,min_field_len,data_mask
from circ_slip_field 
where circ_slip = 'waive' and location = @copy_loc

So I added the following line to the beginning and then copied the original query three times, replacing the two instances of 'waive' with 'payment' and 'refund' respectively.

 declare @copy_loc varchar(7), @new_loc varchar(7) 
 select @copy_loc = 'COPY LOCATION' 
 select @new_loc = 'NEW LOCATION'

I also removed the two select variable statements (@copy_loc and @new_loc) since they have already been declared.

Any thoughts on why this did not work for me? I would be greatly appreciative. Needless to say I'm quite new to SQL in general.

** EDIT: by "did not work" I meant the query ran without errors but did not make any changes to the NEW LOCATION.

* 2nd EDIT: I think the issue may be with the "go" command. In order to have the variables work throughout I need to remove the 'go' from my three replicated queries.

Notice @copy_loc and @new_loc are defined as varchar(7), but you're putting 12 characters into them. They're truncated and won't match the fields in the table. Make the variables varchar(50). Don't worry, it won't use more space than it needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM