T-SQL capturing Linked server name as a result column - sql

How can I capture the (linked) server (in this case Morpheus) name as a column of the result. I do not want to define the Server name in the query itself.
exec("
select
COMNO
,T$CPLS ""Catalog""
,T$CUNO ""Customer ID.""
,T$CPGS ""Price Group""
,T$ITEM ""Item Code""
,T$UPCD UPC
,T$DSCA ""Description""
,T$WGHT ""Weight""
,T$SHIP ""Shipping Indicator""
,nvl(T$STDT,to_char(sysdate,'YYYY-MM-DD')) ""From""
,nvl(case T$TDAT
when '4712-01-01' then ' '
when null then ' '
else t$tdat
end,' ') ""To""
,nvl(t$qanp,99999999) ""Qty.""
,T$PRIC ""List Price""
,T$DISC ""Discount""
,to_char(round(t$pric * (1-t$disc/100),2),99999.99) ""Net""
,Source ""Source""
from Table(edi.ftCompositCatalog(?,?,?)) --where trim(t$item)='105188-041'
order by Source,t$cpgs,t$item",'010','145','000164') at morpheus

If, when running your query, you already know what linked server you are pointing to, then just include that as a string literal in your result:
exec("
select
'morpheus' ""Server Name""
,T$CPLS ""CATALOG""
...
Even if the linked server name is being stored in a variable, you can do this easily since you're building your query string dynamically.
If, as you say, you don't want to define it as a string literal, here is a normal way to get the host (server) name in Oracle:
SELECT SYS_CONTEXT ('USERENV', 'SERVER_HOST') FROM DUAL;
If you want to embed this as a subquery or inline view in your query, I think it would work.
*Please note that some organizations & dba's do not want you to know anything about the backend environment for security reasons, but assuming you have no roadblock there, this should work.

Related

find diffrences between 2 tables sql and how can i get the changed value?

i have this query
insert into changes (id_registro)
select d2.id_registro
from daily2 d2
where exists (
select 1
from daily d1
where
d1.id_registro = d2.id_registro
and (d2.origen, d2.sector, d2.entidad_um, d2.sexo, d2.entidad_nac, d2.entidad_res,
d2.municipio_res, d2.tipo_paciente,d2.fecha_ingreso, d2.fecha_sintomas,
d2.fecha_def, d2.intubado, d2.neumonia, d2.edad, d2.nacionalidad, d2.embarazo,
d2.habla_lengua_indig, d2.diabetes, d2.epoc, d2.asma, d2.inmusupr, d2.hipertension,
d2.otra_com, d2.cardiovascular, d2.obesidad,
d2.renal_cronica, d2.tabaquismo, d2.otro_caso, d2.resultado, d2.migrante,
d2.pais_nacionalidad, d2.pais_origen, d2.uci )
<>
(d1.origen, d1.sector, d1.entidad_um, d1.sexo, d1.entidad_nac, d1.entidad_res,
d1.municipio_res, d1.tipo_paciente, d1.fecha_ingreso, d1.fecha_sintomas,
d1.fecha_def, d1.intubado, d1.neumonia, d1.edad, d1.nacionalidad, d1.embarazo,
d1.habla_lengua_indig, d1.diabetes, d1.epoc, d1.asma, d1.inmusupr, d1.hipertension,
d1.otra_com, d1.cardiovascular, d1.obesidad,
d1.renal_cronica, d1.tabaquismo, d1.otro_caso, d1.resultado, d1.migrante,
d1.pais_nacionalidad, d1.pais_origen, d1.uci ))
it results in an insersion data that doesn't exist in another table, that's fine. but i want know exactly which field has changed to store it in a log table
You don't mention precisely what you expect to see in your output but basically to accomplish what you're after you'll need a long sequence of CASE clauses, one for each column
e.g. one approach might be to create a comma-separated list of the column names that have changed:
INSERT INTO changes (id_registro, column_diffs)
SELECT d2.id_registro,
CONCAT(
CASE WHEN d1.origen <> d2.origen THEN 'Origen,' ELSE '' END,
CASE WHEN d1.sector <> d2.sector THEN 'Sector,' ELSE '' END,
etc.
Within the THEN part of the CASE you can build whatever detail you want to show
e.g. a string showing before and after values of the columns CONCAT('Origen: Was==> ', d1.origen, ' Now==>', d2.origen). Presumably though you'll also need to record the times of these changes if there can be multiple updates to the same record throughout the day.
Essentially you'll need to decide what information you want to show in your logfile, but based on your example query you should have all the information you need.

SQL query with "as" keyword

I have a below SQL query running in one of my project. I am struggling to understand the "as" concept here. In the result "user_key" and "user_all" are appearing as empty. Where as at the front end "user_all" is the combination of "rx.ord_by_userid" + "rx.ord_by_inst_id,"
SELECT rx.rx_id,
rx.pt_visit_id,
rx.pt_id,
pt_visit.date_time_sch,
' ' as print_dea_ind,
' ' as phys_rx_label,
rx.ord_by_userid,
rx.ord_by_inst_id,
' ' as user_key,
pt_visit.visit_inst_id,
' ' as user_all,
' ' as tp_agt_ind,
FROM rx LEFT OUTER JOIN tx_pln ON rx.tp_name = tx_pln.tp_name AND rx.tp_vers_no = tx_pln.tp_vers_no, pt_visit
WHERE ( pt_visit.pt_visit_id = rx.pt_visit_id ) and
( pt_visit.pt_id = rx.pt_id ) and
( ( rx.pt_id = :pt_id ) and
( rx.rx_id = :rx_id ) )
Thanks.
I think when they query database, they need two fields called "user_key" and "user_all" with empty value for some purpose. However, in the front end, they need to display column "user_all" with the combination of "rx.ord_by_userid" + "rx.ord_by_inst_id" because of business rule.
The meaning of "AS" is just setting the alias of any field which is needed to have a new name. In this situation, new columns "user_key" and "user_all" are set with empty value.
AS just provides the field in the data set a name, or in SQL terms, an alias. In PB, this is usually done so that the DataWindow gives it a consistent, easy name. That is all that AS does.
The other part of your mystery is how these get populated with non-blank values. You were assuming this was done in the SQL with AS, but we can assure you that is not the case. Most likely, this value is being set in a script that fires in the client after the Retrieve() (if I were to bet, I'd bet a script on the DataWindow control, maybe RetrieveRow or RetrieveEnd).

Apex parse error when creating SQL query with sql function

I have the following function:
CREATE OR REPLACE FUNCTION calc_a(BIDoctor number) RETURN number
IS
num_a number;
BEGIN
select count(NAppoint)
into num_a
from Appointment a
where BIDoctor = a.BIDoctor;
RETURN num_a;
END calc_a;
What we want is adding a column to a report that shows us the number of appointments that doc have.
select a.BIdoctor "NUM_ALUNO",
a.NameP "Nome",
a.Address "Local",
a.Salary "salary",
a.Phone "phone",
a.NumberService "Curso",
c.BIdoctor "bi",
calc_media(a.BIdoctor) "consultas"
FROM "#OWNER#"."v_Doctor" a, "#OWNER#"."Appointment" c
WHERE a.BIdoctor = c.BIdoctor;
and we got this when we are writing the region source on apex.
But it shows a parse error, I was looking for this about 2 hours and nothing.
Apex shows me this:
PARSE ERROR ON THE FOLLOWING QUERY
This is probably because of all your double quotes, you seem to have randomly cased everything. Double quotes indicate that you're using quoted identifiers, i.e. the object/column must be created with that exact name - "Hi" is not the same as "hi". Judging by your function get rid of all the double quotes - you don't seem to need them.
More generally don't use quoted identifiers. Ever. They cause far more trouble then they're worth. You'll know when you want to use them in the future, if it ever becomes necessary.
There are a few more problems with your SELECT statement.
You're using implicit joins. Explicit joins were added in SQL-92; it's time to start using them - for your future career where you might interact with other RDBMS if nothing else.
There's absolutely no need for your function; you can use the analytic function, COUNT() instead.
Your aliases are a bit wonky - why does a refer to doctors and c to appointments?
Putting all of this together you get:
select d.bidoctor as num_aluno
, d.namep as nome
, d.address as local
, d.salary as salary
, d.phone as phone
, d.numberservice as curso
, a.bidoctor as bi
, count(nappoint) over (partition by a.bidoctor) as consultas
from #owner#.v_doctor a
join #owner#.appointment c
on d.bidoctor = a.bidoctor;
I'm guessing at what the primary keys of APPOINTMENT and V_DOCTOR are but I'm hoping they're NAPPOINT and BIDOCTOR respectively.
Incidentally, your function will never have returned the correct result because you haven't limited the scope of the parameter in your query; you would have just counted the number of records in APPOINTMENT. When you're naming parameters the same as columns in a table you have to explicitly limit the scope to the parameter in any queries you write, for instance:
select count(nappoint) into num_a
from appointment a
where calc_a.bidoctor = a.bidoctor; -- HERE

looking for db2 text function or method I can do a text contain rather than like

I'm looking for a db2 function that does a text contain search. At present I am running the following query against the data below....
SELECT distinct
s.search_id,
s.search_heading,
s.search_url
FROM repman.search s, repman.search_tags st
WHERE s.search_id = st.search_id
AND ( UPPER(s.search_heading) LIKE (cast('%REPORT%' AS VARGRAPHIC(32)))
OR (UPPER(st.search_tag) LIKE cast('%REPORT%' AS VARGRAPHIC(32)))
)
ORDER BY s.search_heading;
Which returns...
But if I change the search text to %REPORTS% rather than %REPORT% (which I need to do) the like search does not work and I get zero results.
I read a link that used a function named CONTAINS like below but when trying to use the function I get an error.
SELECT distinct
s.search_id,
s.search_heading,
s.search_url
FROM repman.search s, repman.search_tags st
WHERE s.search_id = st.search_id
AND CONTAINS(s.search_heading, 'REPORTS') = 1
Has anynoe got any suggestions? I'm on db2 version DB2/LINUXPPC 9.1.6.
Thanks
In order to look for a pattern in a string, you can use Regular Expressions. They are built-in DB2 with xQuery since DB2 v9. There are also other ways to do that. I wrote an article in my blog (in Spanish that you can translate) about Regular Expressions in DB2.
xmlcast(xmlquery('fn:matches(\$TEXT,''^[A-Za-z 0-9]*$'')')

My SCCM 2007 SQL Web Report is not displaying results

I created an SCCM SQL report using SQL Management Studio. I then created the following prompts for my Asset Management Office to use on the web report: Publisher, Display Name, and Version.
The Display Name and the Version prompts are both optional.
I receive no syntax errors or anything, but I receive absolutely no results whatsoever when I click on the Display button to produce the web report.
Here is my SQL code:
==================================================================================
SELECT dbo.v_R_System.Netbios_Name0, dbo.v_GS_ADD_REMOVE_PROGRAMS.DisplayName0, dbo.v_GS_ADD_REMOVE_PROGRAMS.Version0,
dbo.v_GS_ADD_REMOVE_PROGRAMS.Publisher0
FROM dbo.v_R_System INNER JOIN
dbo.v_GS_ADD_REMOVE_PROGRAMS ON dbo.v_R_System.ResourceID = dbo.v_GS_ADD_REMOVE_PROGRAMS.ResourceID
WHERE dbo.v_GS_ADD_REMOVE_PROGRAMS.DisplayName0 = #DisplayName AND dbo.v_GS_ADD_REMOVE_PROGRAMS.Version0 = #Version AND dbo.v_GS_ADD_REMOVE_PROGRAMS.Publisher0 = #Publisher
Order by dbo.v_GS_ADD_REMOVE_PROGRAMS.DisplayName0 ASC
==================================================================================
I run my report and in the Publisher prompt, I type in something like %Autodesk% and then I click the Display button, and absolutely nothing is displayed. I can go to another report and look up Autodesk products, but not this one. I am not a well versed SQL guy, so if anyone can help me that would be great.
Thanks
% signs often mean wildcards. They are used with the like keyword. You have equal signs. In other words,
where DisplayName like '%fred%'
will return fred, freddie, frederick, etc. However,
where DisplayName = '%fred%'
will only return %fred%
AHHHH I see what you were talking about Dan.
Disregard my last statement/inquiry everyone, I got my code working now. My Prompt #variables' SQL code was not configured properly to work with the "Like" constant so I modified my main SQL code to be this:
==================================================================================
Select Distinct dbo.v_R_System.Netbios_Name0, dbo.v_GS_ADD_REMOVE_PROGRAMS.DisplayName0, dbo.v_GS_ADD_REMOVE_PROGRAMS.Version0, dbo.v_GS_ADD_REMOVE_PROGRAMS.Publisher0
FROM dbo.v_R_System
Join dbo.v_GS_ADD_REMOVE_PROGRAMS On dbo.v_R_System.ResourceID = dbo.v_GS_ADD_REMOVE_PROGRAMS.ResourceID
Where dbo.v_GS_ADD_REMOVE_PROGRAMS.Publisher0 Like #Publisher Or dbo.v_GS_ADD_REMOVE_PROGRAMS.DisplayName0 Like #DisplayName Or dbo.v_GS_ADD_REMOVE_PROGRAMS.Version0 Like #VersionOrder by dbo.v_GS_ADD_REMOVE_PROGRAMS.DisplayName0 ASC
==================================================================================
Then I had to modify my Prompt SQL code to use the Begin, If, Else, and End statements. I will pick just my #Publisher variable Prompt SQL code since all of my Prompt #variables' SQL code are basically identical.
Here is the SQL code for my Publisher (#Publisher) Prompt:
==================================================================================
Begin
If(#__filterwildcard = '')
Select Distinct Publisher0
From v_Add_Remove_Programs Order By Publisher0
Else
Select Distinct Publisher0
From v_Add_Remove_Programs
Where Publisher0 Like #__filterwildcard
Order By Publisher0
End
==================================================================================
The code I used before for my Prompt #variables was like this which did not work with the "Like" constant in my main SQL code:
==================================================================================
Select Distinct Publisher0
From v_Add_Remove_Programs Order By Publisher0
Where Publisher0 Like #__filterwildcard
Order By Publisher0
==================================================================================
So, apparently using the Begin, If, Else, and End statements allowed for more logic in this query process, therefore allowing me to use the "Like" constant in my main SQL code for the report.