Powershell: Get certain attributes from resultset - sql

In a rather small powershell script, I retrieve data from a sql database using invoke-sqlmd. The output is written into a variable. Later in the script, I want to use only one attribute of this result set in a foreach loop. How can I call on that specific attribute?
If the question was not well asked, please feel free to ask for further information.
This is the sqlcmd:
$SQLcmd = "Select * From (SELECT t.[Initiator] ,t.[EndTime] ,t.StartTime ,CONVERT(NVARCHAR(50), t.StartTime, 111) as Datum ,t.[Result] as Result ,GDI.[Name] ,P.DisplayString ,Pi.DisplayString as DisplayStringDeutsch FROM [M42STORE].$SQL_Table t join [dbo].[GDIEImportClassBase] GDI on GDI.ID = t.ImportSequence left join [dbo].[GDIEImportPickupResult] P on P.Value = t.Result left join [dbo].[GDIEImportPickupResult-CI] Pi on Pi.Owner = P.ID and Pi.LCID = 7 ) Q WHERE Result = '3'"

Related

How to pass value from the textbox to the sql query's parameter

I need some help here.
SET #LotId = '{0}%'
SELECT
coalesce(a.LOT_ID, b.LOT_ID,c.LOT_ID,d.LOT_ID) as LotId,
coalesce(a.CheckIn, b.CheckIn,c.CheckIn,d.CheckIn) as CheckIn,
coalesce(a.CheckOut, b.CheckOut,c.CheckOut,d.CheckOut) as CheckOut,
coalesce(a.StatusDesc, b.StatusDesc,c.StatusDesc,d.StatusDesc) as
StatusDesc
FROM
LOT_LOC_BOND a
LEFT OUTER JOIN
LOT_LOC_IEBT b ON a.LOT_ID = b.LOT_ID
AND a.CheckIn = b.CheckIn
AND a.CheckOut = b.CheckOut
AND a.StatusDesc = b.StatusDesc
LEFT OUTER JOIN
LOT_LOC_MBT c ON b.LOT_ID = c.LOT_D
AND b.CheckIn = c.CheckIn
AND b.CheckOut = c.CheckOut
AND b.StatusDesc = c.StatusDesc
LEFT OUTER JOIN
LOT_LOC_SEAL d ON c.LOT_ID = d.LOT_ID
AND c.CheckIn = d.CheckIn
AND c.CheckOut = d.CheckOut
AND c.StatusDesc = d.StatusDesc
WHERE
a.LOT_ID = #LotId
I need to pass a value which known as Lotid from the textbox to the SQL query parameter, and I don't think the above query is a right way to do that.someone told me that using coalesce is forbidden if you want to pass the parameter.
I really need your help right now. I am using SQL Server 2014 for the query and Asp.net, vb.net in Visual Studio 2010 for the IDE, this system also are using two different pages. The textbox is on the first page and the result will be display at the second page.

MS access using case in transform pivot

I'm trying to print a schedule using a query in access. The problem is when nobody is scheduled for a task the field is left blank. The problem is when nobody is scheduled for a task for the whole duration of the schedule since nobody is assigned for this task some referencing get borked. So my question is can I use a simple CASE in my query to switch a null value on Responsable.ResponsableAbrege for something like ' ' or 'N/A' or am I looking at it from the wrong angle? Here is the code :
TRANSFORM First(Responsable.ResponsableAbrege) AS PremierDeResponsableAbrege
SELECT wCalendrier.Entite, Entite.DescriptionAbrege, Tache.Tache, Fonction.Abréviation, Module.Module, Fonction.NoFonction, Tache.NoTache, First(wCalendrier.PremierResponable) AS PremierDePremierResponable
FROM RecupererResponsable, Fonction INNER JOIN ([Module] INNER JOIN (Équipe INNER JOIN (((wCalendrier INNER JOIN Tache ON wCalendrier.NoTache = Tache.NoTache) INNER JOIN Responsable ON wCalendrier.NoResponsable = Responsable.NoResponsable) INNER JOIN Entite ON wCalendrier.Entite = Entite.Entite) ON (Équipe.NoÉquipe = Responsable.Equipe) AND (Équipe.NoÉquipe = Responsable.Equipe)) ON Module.NoModule = Tache.Module) ON Fonction.NoFonction = Tache.Fonction
GROUP BY wCalendrier.Entite, Entite.DescriptionAbrege, Tache.Tache, Fonction.Abréviation, Module.Module, Fonction.NoFonction, Tache.NoTache
PIVOT "D" & [Sequence] In ("D1","D2","D3","D4","D5","D6","D7","D8","D9","D10","D11","D12","D13","D14","D15");
In MS Access SQL instead of CASE you should use either IIF or switch
iif(isnull(FIRST(Responsable.ResponsableAbrege)),'N/A', FIRST(Responsable.ResponsableAbrege))

How to create a query using Access from a given SQL

Someone gave me the following SQL and wants me to do a query using Access, so that it returns the information that they need. All dbo_**** are databases where they get the information from.
I tried to do the following SQL using a design view, but its not working, the datasheet(table) doesnt match the information.
I get lost in the lines LEFT OUTER JOIN ... I dont know what to do with anything after that. Can someone help me, please ?
Or if someone someone can edit the SQL so that it works on Access just copying in the SQL view mode.
Thank you.
Declare #data datetime
set #data = '2013-12-31'
--Fundos
SELECT
RelCliSFN.CdCrt,
MC5.Nome 'NomeCarteira',
MC5.CGC 'CNPJCarteira',
player_adm.NomeCurto 'Administrador',
RelCliSFN.Cliente,
CE5.Nome 'NomeCliente',
CE5.CPFCGC 'CPF/CNPJCliente',
VigRelCliSFN.DtIni,
VigRelCliSFN.DtFim
FROM
RelCliSFN
Inner JOIN MC5 ON MC5.Carteira = RelCliSFN.CdCrt
INNER JOIN MC5Auxiliar ON MC5.Carteira = MC5Auxiliar.Carteira
Inner Join VigRelCliSFN ON RelCliSFN.IdRelCliSFN = VigRelCliSFN.IdRelCliSFN
Inner Join CE5 ON CE5.Cliente=RelCliSFN.Cliente
LEFT OUTER JOIN PlayAdmxMC5 ON MC5.Carteira = PlayAdmxMC5.CdCrt AND PlayAdmxMC5.DtIniVig =
(SELECT MAX(DtIniVig) FROM PlayAdmxMC5 WHERE MC5.Carteira = CdCrt AND DtIniVig < MC5.DataAtual)
INNER JOIN Player player_adm ON PlayAdmxMC5.IdPlayAdm = player_adm.ID
WHERE
--MC5Auxiliar.bNaoExpCCSFN is null
((VigRelCliSFN.DtIni <= #data)
and ((VigRelCliSFN.DtFim >= #data) or (VigRelCliSFN.DtFim is null)))
and MC5.CGC <> 0
and CE5.Assessor not in (17, 99)
and CE5.CPFCGC <>0
and MC5.TipoCarteira <> 4
--and RelCliSFN.CdCrt = 3`
As the others already mentioned, your query has MS SQL-Server syntax. So there are three ways you could solve your problem.
Solution 1:
Create a view in the SQL-Server database.
To do this, open your SQL-Server Management Studio. Go to YourServer > databases > YourDatabase > views. Right click on "views" and then select "new view...". Close the "add table" window. Copy your sql-code into the sql window (the one saying "SELECT FROM"). You will get an error message saying that your code can't be displayed. Ignore it. Save your view. You can connect it to your Access database the same way you would connect a table.
Solution 2:
Use a SQL-Passthrough query in Access.
This is a bit complicated to explain, because almost every Access version has a slightly different menu. I'll explain it for Access 2007.
Create a new query. Close the "add table" window. Choose "Pass-Through" from the design menu (I don't know exactly if the menu label of the english version is "design". In my version it says "Entwurf"). Open the properties window. Insert the correct ODBC string. The easiest way to get an ODBC-string is to use one from an existing ODBC-table. Go to the VBA immediate window (Ctrl + G) and write ?CurrentDb.TableDefs("YourTable").Connect (instead of YourTable you have to insert the name of your ODBC-table). Press Return. You should get something like
ODBC;DSN=YourConnection;Description=IAmAnODBCConnection;APP=2007 Microsoft Office system;DATABASE=YourDatabase
Copy this string into the ODBC property of your query. Be sure the option "returns records" is set to "Yes". Copy you SQL into the query and save it.
Solution 3:
Convert your SQL Server syntax to Access syntax. Before doing this, you have to connect every table which is used in the query. I can't test my syntax conversion, but this should work:
PARAMETERS data DateTime = #2013-12-31#;
SELECT
RelCliSFN.CdCrt,
MC5.Nome "NomeCarteira",
MC5.CGC "CNPJCarteira",
player_adm.NomeCurto "Administrador",
RelCliSFN.Cliente,
CE5.Nome "NomeCliente",
CE5.CPFCGC "CPF/CNPJCliente",
VigRelCliSFN.DtIni,
VigRelCliSFN.DtFim
FROM
RelCliSFN
Inner JOIN MC5 ON MC5.Carteira = RelCliSFN.CdCrt
INNER JOIN MC5Auxiliar ON MC5.Carteira = MC5Auxiliar.Carteira
Inner Join VigRelCliSFN ON RelCliSFN.IdRelCliSFN = VigRelCliSFN.IdRelCliSFN
Inner Join CE5 ON CE5.Cliente=RelCliSFN.Cliente
LEFT OUTER JOIN PlayAdmxMC5 ON MC5.Carteira = PlayAdmxMC5.CdCrt AND PlayAdmxMC5.DtIniVig =
(SELECT MAX(DtIniVig) FROM PlayAdmxMC5 WHERE MC5.Carteira = CdCrt AND DtIniVig < MC5.DataAtual)
INNER JOIN Player player_adm ON PlayAdmxMC5.IdPlayAdm = player_adm.ID
WHERE
((VigRelCliSFN.DtIni <= [data])
and ((VigRelCliSFN.DtFim >= [data]) or (VigRelCliSFN.DtFim is null)))
and MC5.CGC <> 0
and CE5.Assessor not in (17, 99)
and CE5.CPFCGC <>0
and MC5.TipoCarteira <> 4
Well I don't know if Access can handle the equation of PlayAdmxMC5.DtIniVig = (Subquery). If it doesn't work, you should create a new query containing only the subquery and then connect it to this query.
MAIN CODE I am using
SELECT dbo_RelCliSFN.CdCrt, dbo_MC5.Nome AS NomeCarteira, dbo_MC5.CGC AS CNPJCarteira, dbo_RelCliSFN.Cliente, dbo_CE5.Nome AS NomeCliente, dbo_CE5.CPFCGC AS [CPF/CNPJCliente], dbo_VigRelCliSFN.DtIni, dbo_VigRelCliSFN.DtFim
FROM ((((dbo_RelCliSFN INNER JOIN dbo_CE5 ON dbo_RelCliSFN.Cliente = dbo_CE5.Cliente) INNER JOIN dbo_MC5 ON dbo_RelCliSFN.CdCrt = dbo_MC5.Carteira) INNER JOIN dbo_MC5Auxiliar ON dbo_MC5.Carteira = dbo_MC5Auxiliar.Carteira) INNER JOIN dbo_VigRelCliSFN ON dbo_RelCliSFN.IdRelCliSFN = dbo_VigRelCliSFN.IdRelCliSFN) LEFT JOIN Query1 ON dbo_MC5.Carteira = Query1.CdCrt
GROUP BY dbo_RelCliSFN.CdCrt, dbo_MC5.Nome, dbo_MC5.CGC, dbo_RelCliSFN.Cliente, dbo_CE5.Nome, dbo_CE5.CPFCGC, dbo_VigRelCliSFN.DtIni, dbo_VigRelCliSFN.DtFim, dbo_MC5.TipoCarteira, dbo_CE5.Assessor
HAVING (((dbo_RelCliSFN.CdCrt)=802) AND ((dbo_MC5.CGC)<>0) AND ((dbo_CE5.CPFCGC)<>0) AND ((dbo_VigRelCliSFN.DtIni)<=#12/31/2013#) AND ((dbo_VigRelCliSFN.DtFim)>=#12/31/2013# Or (dbo_VigRelCliSFN.DtFim) Is Null) AND ((dbo_MC5.TipoCarteira)<>4) AND ((dbo_CE5.Assessor) Not In (17.19)));

Joining on a many to many relationship with LINQ

I have been tasked with converting some old SQL stored procs to LINQ for an EF migration we are doing and Im a little stumped. Given that this is a migration from an existing application the edmx was generated database first. So, I have a SQL statement that I am trying to replicate:
SELECT DISTINCT
d.DeliverySubscriptionId
, d.ContactId
, d.statementMacroId_fk
, m.Name as MacroName
, DeliveryMethod = REPLACE((SELECT DISTINCT
dm2.Name + ',' AS 'data()'
FROM
DeliverySubscription d2
JOIN
StatementMacro m2 on
d2.StatementMacroId_fk = m2.StatementMacroId
JOIN
DeliverySubscription_Method_Rel dmr2 ON
d2.DeliverySubscriptionId = dmr2.DeliverySubscriptionId_Fk
JOIN
dbo.DeliveryMethod dm2 ON
dmr2.DeliveryMethodId_Fk = dm2.DeliveryMethodId
WHERE
d.DeliveryConfigurationId_fk = #configurationId
AND
d.IsActive = 1
AND
D.DeliverySubscriptionId = D2.DeliverySubscriptionId FOR XML PATH('')) + '$', ',$', '')
FROM
DeliverySubscription d
INNER JOIN
StatementMacro m ON
d.StatementMacroId_fk = m.StatementMacroId
JOIN
DeliverySubscription_Method_Rel dmr ON
d.DeliverySubscriptionId = dmr.DeliverySubscriptionId_Fk
JOIN dbo.DeliveryMethod dm ON
dmr.DeliveryMethodId_Fk = dm.DeliveryMethodId
WHERE
d.DeliveryConfigurationId_fk = #configurationId
AND
d.IsActive = 1
In particular the part that I have having an issue with is the JOIN DeliverySubscription_Method_Rel which is a relationship table representing a many to many relationship between DeliverySubscription and DeliveryMethod.
This shows up as:
[DeliverySubscription] * ---- * [Delivery Method]
in the database diagram in the edmx. No DeliverySubscription_Method_Rel entity is created. As you can see in the SQL statement the JOIN is directly on the relationship table, but I cant seem to figure out how to replicate this in LINQ. Please help!
UPDATE:
So looking around the web I found a similar example which suggested doing something like this:
from s in Context.DeliverySubscriptions
from dm in s.DeliveryMethods
join sm in Context.StatementMacroes on s.StatementMacroId_Fk equals sm.StatementMacroId
where s.DeliveryConfigurationId_Fk == configurationId
select new DeliverySubscription_dto
{
DeliverySubscriptionId = s.DeliverySubscriptionId,
QubeContactId = s.QubeContactId,
statementMacroId_fk = s.StatementMacroId_Fk,
MacroName = sm.Name,
DeliveryMethod = dm.Name.Replace("$","").Replace(",$","")
}
...however because I still have a lot of other things to change in the application thus far I am unable to build in order to test this yet so I just wanted to run this buy you all to see if this seems correct.
That query is a beast. If you weren't having any performance problems with it, I would probably just add it to the datamodel and use linq/EF to call it.

Problem with adding custom sql to finder condition

I am trying to add the following custom sql to a finder condition and there is something not quite right.. I am not an sql expert but had this worked out with a friend who is..(yet they are not familiar with rubyonrails or activerecord or finder)
status_search = "select p.*
from policies p
where exists
(select 0 from status_changes sc
where sc.policy_id = p.id
and sc.status_id = '"+search[:status_id].to_s+"'
and sc.created_at between "+status_date_start.to_s+" and "+status_date_end.to_s+")
or exists
(select 0 from status_changes sc
where sc.created_at =
(select max(sc2.created_at)
from status_changes sc2
where sc2.policy_id = p.id
and sc2.created_at < "+status_date_start.to_s+")
and sc.status_id = '"+search[:status_id].to_s+"'
and sc.policy_id = p.id)" unless search[:status_id].blank?
My find statement:
Policy.find(:all,:include=>[{:client=>[:agent,:source_id,:source_code]},{:status_changes=>:status}],
:conditions=>[status_search])
and I am getting this error message in my log:
ActiveRecord::StatementInvalid (Mysql::Error: Operand should contain 1 column(s): SELECT DISTINCT `policies`.id FROM `policies` LEFT OUTER JOIN `clients` ON `clients`.id = `policies`.client_id WHERE ((((policies.created_at BETWEEN '2009-01-01' AND '2009-03-10' OR policies.created_at = '2009-01-01' OR policies.created_at = '2009-03-10')))) AND (select p.*
from policies p
where exists
(select 0 from status_changes sc
where sc.policy_id = p.id
and sc.status_id = '2'
and sc.created_at between 2009-03-10 and 2009-03-10)
or exists
(select 0 from status_changes sc
where sc.created_at =
(select max(sc2.created_at)
from status_changes sc2
where sc2.policy_id = p.id
and sc2.created_at < 2009-03-10)
and sc.status_id = '2'
and sc.policy_id = p.id)) ORDER BY clients.created_at DESC LIMIT 0, 25):
what is the major malfunction here - why is it complaining about the columns?
The conditions modifier is expecting a condition (e.g. a boolean expression that could go in a where clause) and you are passing it an entire query (a select statement).
It looks as if you are trying to do too much in one go here, and should break it down into smaller steps. A few suggestions:
use the query with find_by_sql and don't mess with the conditions.
use the rails finders and filter the records in the rails code
Also, note that constructing a query this way isn't secure if the values like status_date_start can come from users. Look up "sql injection attacks" to see what the problem is, and read the rails documentation & examples for find_by_sql to see how to avoid them.
Ok, I've managed to retool this so it is more friendly to a conditions modifier and I think it is doing the sql query correctly.. however, it is returning policies that when I try to list the current status (the policy.status_change.last.status) it is set to the same status used in the query - which is not correct
here is my updated condition string..
status_search = "status_changes.created_at between ? and ? and status_changes.status_id = ?) or
(status_changes.created_at = (SELECT MAX(sc2.created_at) FROM status_changes sc2
WHERE sc2.policy_id = policies.id and sc2.created_at < ?) and status_changes.status_id = ?"
is there something obvious to this that is not returning all of the remaining associated status changes once it finds the one in the query?
here is the updated find..
Policy.find(:all,:include=>[{:client=>[:agent,:source_id,:source_code]},:status_changes],
:conditions=>[status_search,status_date_start,status_date_end,search[:status_id].to_s,status_date_start,search[:status_id].to_s])