Select Specific Column from a Linked Server Table - sql

I have the following C# code to select a column from a table that is on a linked server:
var query2 = $#"select [FileName] from [AMS_H2H].[H2H].[dbo].[FileReconciliation] where ProductCode = #productCode";
LayZConnection(); //make the db connection
var candidates = _dbConnection.Query<int>(query2, new { productCode = "ACHDH" });
When running it, I get the following error:
"Input string was not in a correct format."
If my query is instead the following, where I select all columns, it works:
var query2 = $#"select * from [AMS_H2H].[H2H].[dbo].[FileReconciliation]
What is the correct format to select just the FileName. Btw, the first query works fine from MSSMS.

You're specifying a type of int in Query<int>, which will cause Dapper to try and map the result of the query to an integer, however your query is returning a filename in select [FileName], which would suggest that it is a string.
Changing the type Query<string> should solve the issue.
More information on Dapper's Query method is available in Dapper's documentation

Related

GORM not returning results, but when I run the SQL query in my database client, records come back

My GORM query looks a little like this:
selectCallSQL = "SELECT * from callautomation_schedule WHERE id = ?"
testSelect = "SELECT * FROM callautomation_schedule WHERE next_planned_call > date_trunc('minute', now())"
func SelectCall(id int) *CallSchedule{
var result CallSchedule
connection.Raw(selectCallSQL, id).Scan(&result)
return &result
}
func SelectCall2() *CallSchedule{
var result CallSchedule
connection.Raw(testSelect).Scan(&result)
return &result
}
The first function returns a result as expected, however, the second function does not.
If I run the testSelect SQL in my database client, I do get a result. Why is this happening?
The issue I discovered was with my connection string and column setup. I was using the type TIMESTAMP NO TIMEZONE in my table schema, but in my connection string, I was connecting via the Asia Timezone.
Annoying bug, but fixed now!

How to query ODBC with Dapper with multiple parameters including a WHERE IN?

I've hit an issue using Dapper to query an ODBC provider. The query in question is supplied several parameters. One of the parameters is used to populate a WHERE IN operator.
So far I've tried supplying the query with: DynamicParameters, ? regular parameters, ?name? pseudo-positional parameters and some combinations of these.
SELECT companyId
,projectId
,contractId
,status
FROM certificate
WHERE companyId = ?companyId?
AND projectId = ?projectId?
AND contractId = ?contractId?
AND invoiceId IN ?invoiceIds?
var results = await connection
.QueryAsync<Certificate>(query, new { companyId, projectId, contractId, invoiceIds = new string[] { '1a', '1b', '2a' }});
Expected results are several rows being returned. If I hardcode the query with it's parameters it works fine, so the data I'm supplying should return rows.
Instead I'm getting an exception with the following message:
ERROR [07001] [DataDirect][ODBC Progress OpenEdge Wire Protocol driver]Value has not been specified for parameter 4.
ERROR [07001] [DataDirect][ODBC Progress OpenEdge Wire Protocol driver]Value has not been specified for parameter 5.
If that is your code, then your code doesn't compile. You are not supplying any values for the first three parameters and you are giving illegal characters instead of string in the fourth parameter. I see no reason why this shouldn't work:
var results = await connection
.QueryAsync<Certificate>(query,
new { companyId=1, projectId=1, contractId=1, invoiceIds = new [] { "1a", "1b", "2a" }});

Linq Query in VB

Good Day,
I am querying my database using Linq and I have run into a problem, the query searched a column for a search phrase and based on if the column has the phrase, it then returns the results, The query is below,
Dim pdb = New ProductDataContext()
Dim query =
From a In pdb.tblUSSeries
Join b In pdb.tblSizes_ On a.Series Equals b.Series
Where
a.Series.ToString().Equals(searchString) Or
b.Description.Contains(searchString) Or Not b.Description.Contains(Nothing)
Order By b.Series, b.OrderCode Ascending
Select New CustomSearch With
{
.Series = a.Series,
.SeriesDescription= a.Description,
.Coolant = a.Coolant,
.Material = a.Material,
.Standard = a.Standard,
.Surface = a.Surface,
.Type = a.Type,
.PointAngle = a.PointAngle,
.DiaRange = a.DiaRange,
.Shank = b.Shank,
.Flutes = b.Flutes,
.EDPNum = b.EDPNum,
.SizesDescription = b.Description,
.OrderCode = b.OrderCode
}
Return query
I think the problem is that, in the table certain rows are NULL, so when it is checking the column for the phrase and it encounters a row that is null it, breaks and returns this error,
The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
I have ran this query against another column that has all the rows populated with data and it returns the results ok.
So my question is how can I write it in VB to query the db with the supplied searchstring and return the results, when some of the rows in the columns have null values.
Any help would be great.
The exception occurs when you make the projection (i.e. select new CustomSearch)
And yes your trying to assign Null to some int property
(Not sure which one of your properties that is)
one of 2 choices :
1) Use nullalbe types for your properties (or just that one property).
2) project with an inline If ( ?? in C#) , I don't know VB so don't catch me on the syntax.
Taking Series just as an example i don't know if it's an int or if that's the problematic property
Select New CustomSearch With
{
.Series = If(a.Series Is Nothing,0, CInt(a.Series))
}
In C#
Select new CustomSearch
{
Series = a.Series ?? 0;
}

SQL attribute name in parameterized query

I am using following function for retrieving record on choice. I gave table my column name and value and it shows the result. but the problem is, Its not getting column name as parameter like:
public List<Products> ListAllProducts(string searchOption, string searchValue)
{
db.ClearParameters();
db.AddParameter(db.MakeInParam("#ColumnName", DbType.String, 50, searchOption));
db.AddParameter(db.MakeInParam("#Value", DbType.String, 50, searchValue));
string query = #"SELECT *
FROM [Products]
WHERE #ColumnName LIKE '%'+#Value+'%'";
ds = db.GetDataSet(query);
//Rest of code but above query is not executing
}
but when I use query like this:
string query = #"SELECT *
FROM [Products]
WHERE "+searchOption+" LIKE '%'+#Value+'%'";
It runs fine and give me result. I read this, this and this one specially, but got no idea.
Kindly guide me.
Parameters can be used in place of values inside expressions, and for nothing else: in particular, you cannot use parameters to denote table names, column names, sort order specifiers, or other parts of SQL statement that are not values.
Your non-parametersized query works, because searchOption is copied into your SQL, and becomes part of the query string.
If you need to build a query that changes conditions based on a parameter, you need to change the condition to account for all possible values of #ColumnName, like this
string query = #"SELECT *
FROM [Products]
WHERE (#ColumnName='FirstName' AND FirstName LIKE '%'+#Value+'%')
OR (#ColumnName='LastName' AND LastName LIKE '%'+#Value+'%')
OR (#ColumnName='Location' AND Location LIKE '%'+#Value+'%')";
or fall back on generating your query dynamically. As long as searchOption is not coming from user's input directly, you are safe from SQL injection attacks even though your SQL is generated dynamically.
While Trying, I came across following option and posted in answer ,so other may get benifit of this.
string query = String.Format(
#"SELECT *
FROM [Products]
WHERE {0} LIKE '%'+#Value+'%'", searchOption
);
So the complete function becomes:
public List<Products> ListAllProducts(string searchOption, string searchValue)
{
db.ClearParameters();
db.AddParameter(db.MakeInParam("#Value", DbType.String, 50, searchValue));
string query = String.Format(
#"SELECT *
FROM [Products]
WHERE {0} LIKE '%'+#Value+'%'", searchOption
);
ds = db.GetDataSet(query);
//Rest of code
}

dataSet.xsd query select where in

In SQL it works fine
SELECT NOID, NO_DOSSOIN, NO_ORDO, POSOLOG FROM dbo.ESPMEDS_ORDO_SORTIR
WHERE NO_DOSSOIN = #NO_DOSSOIN AND NOID IN (#NOIDIN)
example
SELECT NOID, NO_DOSSOIN, NO_ORDO, POSOLOG FROM dbo.ESPMEDS_ORDO_SORTIR
WHERE NO_DOSSOIN = 10 AND NOID IN (16,17)
But as I put this in a dataset.xsd query I don't get the same output, I cannot put more than one id into NOIDIN parameter because the NOID type is integer
so my file DataSet.xsd only work like this:
SELECT NOID, NO_DOSSOIN, NO_ORDO, POSOLOG FROM dbo.ESPMEDS_ORDO_SORTIR
WHERE NO_DOSSOIN = 10 AND NOID IN (16)
the error says I cannot convert data from string to int
You should just separate the NOIDIN. Don't expect to be able to pass an Int32 that looks like 16,17 it will always be seen as a string by this wizard and won't compile at all if you execute it from the code.
The easiest option for you is to pass the range in two values like this :
SELECT NOID, NO_DOSSOIN, NO_ORDO, POSOLOG FROM dbo.ESPMEDS_ORDO_SORTIR
WHERE NO_DOSSOIN = #NO_DOSSOIN AND NOID IN (#NOIDSTART, #NOIDEND)
And then assign :
#NOIDSTART = 16
#NOIDEND = 17
If you're parameters are dynamic you should read this article which pretty much covers the subject.