Whenever I put case in my query it gives an error of "Specified cast is not valid" in linq to sql C# but
Its working fine in Sql server 2008.
Below query iam using
select Prod_StyleID,S.STYLECODE,STYLENAME,CATEGORYNAME,VENDORNAME,STYLESTATUS,Gendername,
STYLEDESCRIPTION,SHORTDESCRIPTION1,SHORTDESCRIPTION2,SHORTDESCRIPTION3,SHORTDESCRIPTION4,STYLEPRICE,
BRANDNAME,VENDORSTYLECODE,CATEGORYTYPE,1 as ColorATtribute,1 as SizeAttribute,
case when s.styleprice = '0' then sp.regularprice when s.styleprice = '1' then
sp.saleprice else closeoutprice end as Regularprice from prod_style S inner join prod_styleprice SP on s.stylecode = sp.stylecode where (S.STYLECODE LIKE #stylecode+'%' OR S.VENDORSTYLECODE like #stylecode+'%')
and S.CATEGORYNAME <> 'Made to Order' and S.STYLESTATUS = 'Active' and sp.pricefrom ='1'
please help
Related
I try to fill a repeater control's datasource through the following VB code :
Dim queryString As SparqlParameterizedString = New SparqlParameterizedString()
For Each nsPrefix In UrlManager.namespaces.Keys
queryString.Namespaces.AddNamespace(nsPrefix, New Uri(UrlManager.namespaces(nsPrefix)))
Next
queryString.CommandText = commandText
Dim parser As New SparqlQueryParser()
Dim query = parser.ParseFromString(queryString)
Dim r As SparqlResultSet = g.ExecuteQuery(query)
If r.Count > 0 Then
datasource = r
Else
datasource = Nothing
End If
where variable g is my working graph
I work with the same query
SELECT DISTINCT ?context ?label {
?s a my:Client .
?s rdfs:label ?label .
BIND ( IF(EXISTS {?s rdf:type my:Subscriber}, 1, 0) AS ?priority )
} ORDER BY DESC(?priority) ASC(?label)
Whenever I try this vb code in a simple aspx page, it works correctly but if fails on the repeater OnLoad event with a VDS.RDF.Query.RdfQueryException: Cannot add a Set to the Null Multiset
It seems the error is caused by the BIND ( IF(EXISTS {?s rdf:type my:Subscriber}, 1, 0) AS ?priority ) clause: if I remove it, my repeater behaves as expected!
Any idea why the exception occurs and how to correct it ?
This may be related to the bug identified by your related question (Sparql issue on BIND clause)
There was a bug in EXISTS when it was used as the child of another expression, if you are able to build from source yourself you will be able to check whether that fix resolves this issue. If you still encounter a problem please file a new bug in the Issue Tracker
I have a .aspx page that has query to and informix database. This query is done via an odbc connection and is put into a datatable. Then this datatable is used as the datasource for a radio button group.
My problem is that for whatever reason the time is being appended to the radio button as "12:00:00 AM". This is odd because the informix field is a date field that does not include the time. If I were to run the query outside of the webpage it returns it without the time... "2012-06-15"
So in summary... what I am getting is: "6/15/2012 12:00:00 AM" and what I want is "06/15/2012"
The query is as follows:
"select DATE(attend_date) as attend_date from soar_major_table where major =? and active<>'N'"
The code that creates the datatable:
string connString;
connString = ConfigurationManager.ConnectionStrings [ "ERP" ].ConnectionString;
OdbcConnection conn = new OdbcConnection ( );
conn.ConnectionString = connString;
string sql = "select DATE(attend_date) as attend_date from soar_major_table where major =? and active<>'N' ";
OdbcCommand command = new OdbcCommand ( );
command.CommandText = sql;
command.Parameters.Add ( new OdbcParameter ( "major", major ) );
command.Connection = conn;
DataTable dt = new DataTable ( );
OdbcDataAdapter dataAdapter = new OdbcDataAdapter ( );
dataAdapter.SelectCommand = command;
try
{
conn.Open ( );
dataAdapter.Fill ( dt );
}
finally
{
if ( conn != null && conn.State == ConnectionState.Open )
{
command.Dispose ( );
dataAdapter.Dispose ( );
conn.Close ( );
}
}
return dt;
And lastly the population of the radio btn group:
if ( dt.Rows.Count > 0 )
{
rdoDate.DataSource = dt;
rdoDate.DataTextField = "attend_date";
rdoDate.DataValueField = "attend_date";
rdoDate.DataBind ( );
}
The problem is upstream of the Informix data server, I believe.
When you execute:
SELECT DATE(attend_date) ...
the server will return that value as a 4-byte integer representing the number of days since 1899-12-31 (so 1900-01-01 was day 1), which is the internal representation of a DATE in Informix.
Something in a higher layer is then treating it as a 'date + time' value and assuming midnight is the time since there was no time component in the date, and is then rubbing salt in the wound by formatting it in am/pm notation.
This will involve client-side tracing of what's going on. My suspicion (not founded on anything except limited knowledge of the ODBC drivers) is that the problem is occurring in the .NET layers rather than the ODBC driver. However, you're way outside my area of expertise once you're above the ODBC layer (and I don't claim great expertise in ODBC).
You may be able to isolate the problem to the client code by using SQLIDEBUG=2:xyz in the environment (you might need to set that with SETNET32 for Windows). If it works at all on Windows (it does on Unix), then you'll end up with a file with a name starting xyz_ followed by various groups of digits and letters. That file can be analyzed by sqliprint and will show you what was sent to the Informix data server and returned to your client. Assuming the SQL was not hacked en route to the server, then you'll see the date returned as a simple date, and the problem is definitively client-side. If the SQL is hacked en route, then that too is a client-side problem.
It at least gives a starting point for debugging.
Look very carefully at the data types of the types your code is using. In particular, some DBMS have a DATE type that includes time information, and you may need to avoid that interpretation. The SQL standard has DATE (no time), TIME (no date) and TIMESTAMP (date and time) types.
I'm using Visual Studio 2010 ASP.NET with C# on .NET 4.0 and SQL Server 2008 R2.
I would like to create a database on the server named WINSRV\SQLSRV.
How do I loop to test for a unique database name?
My default database should be ab. In case this name is taken, I would like to create a database named ab1, and if this one is also taken - ab2 and so forth.
I need it to rum from a web page created in the Visual Studio 2010 ASP.NET C# script, and not from the SQL server management studio.
Thanks.
Declare #Iteration int
Set #Iteration = 0
Declare #DBName varchar(100)
while(#Iteration <> -1)
begin
if(#Iteration = 0)
Set #DBName = 'ab'
Else
Set #DBName = 'ab' + Convert(varchar, #Iteration)
IF NOT EXISTS(select Object_Id from sys.databases where name = 'ab')
Begin
Exec('create database ' + #DBName)
return;
End
Else
Begin
Set #Iteration = #Iteration + 1
End
End
Edit
To Work from C# click here
You will want to check to see if your choices for databases exist:
You can do it primary sql side as so:
IF (EXISTS (SELECT name FROM master.sys.databases WHERE name = 'ab')))
--Do what you need to do
or you could get a list databases and check .net side:
SELECT name FROM master.sys.databases
Hope this helps.
I have this SQL query:
SELECT Sum(ABS([Minimum Installment])) AS SumOfMonthlyPayments FROM tblAccount
INNER JOIN tblAccountOwner ON tblAccount.[Creditor Registry ID] = tblAccountOwner.
[Creditor Registry ID] AND tblAccount.[Account No] = tblAccountOwner.[Account No]
WHERE (tblAccountOwner.[Account Owner Registry ID] = 731752693037116688)
AND (tblAccount.[Account Type] NOT IN
('CA00', 'CA01', 'CA03', 'CA04', 'CA02', 'PA00', 'PA01', 'PA02', 'PA03', 'PA04'))
AND (DATEDIFF(mm, tblAccount.[State Change Date], GETDATE()) <=
4 OR tblAccount.[State Change Date] IS NULL)
AND ((tblAccount.[Account Type] IN ('CL10','CL11','PL10','PL11')) OR
CONTAINS(tblAccount.[Account Type], 'Mortgage')) AND (tblAccount.[Account Status ID] <> 999)
I have created a Linq query:
var ownerRegistryId = 731752693037116688;
var excludeTypes = new[]
{
"CA00", "CA01", "CA03", "CA04", "CA02",
"PA00", "PA01", "PA02", "PA03", "PA04"
};
var maxStateChangeMonth = 4;
var excludeStatusId = 999;
var includeMortgage = new[] { "CL10", "CL11", "PL10", "PL11" };
var sum = (
from account in context.Accounts
from owner in account.AccountOwners
where owner.AccountOwnerRegistryId == ownerRegistryId
where !excludeTypes.Contains(account.AccountType)
where account.StateChangeDate == null ||
(account.StateChangeDate.Month - DateTime.Now.Month)
<= maxStateChangeMonth
where includeMortgage.Contains(account.AccountType) ||
account.AccountType.Contains("Mortgage")
where account.AccountStatusId != excludeStatusId
select account.MinimumInstallment).ToList()
.Sum(minimumInstallment =>
Math.Abs((decimal)(minimumInstallment)));
return sum;
Are they equal/same ? I dont have records in db so I cant confirm if they are equal. In SQL there are brackets() but in Linq I didnt use them so is it ok?
Please suggest.
It is not possible for us to say anything about this, because you didn't show us the DBML. The actual definition of the mapping between the model and the database is important to be able to see how this executes.
But before you add the DBML to your question: we are not here to do your work, so here are two tips to find out whether they are equal or not:
Insert data in your database and run the queries.
Use a SQL profiler and see what query is executed by your LINQ provider under the covers.
If you have anything more specific to ask, we will be very willing to help.
The brackets will be generated by LINQ provider, if necessary.
The simplest way to check if the LINQ query is equal to the initial SQL query is to log it like #Atanas Korchev suggested.
If you are using Entity Framework, however, there is no Log property, but you can try to convert your query to an ObjectQuery, and call the ToTraceString method then:
string sqlQuery = (sum as ObjectQuery).ToTraceString();
UPD. The ToTraceString method needs an ObjectQuery instance for tracing, and the ToList() call already performs materialization, so there is nothing to trace. Here is the updated code:
var sum = (
from account in context.Accounts
from owner in account.AccountOwners
where owner.AccountOwnerRegistryId == ownerRegistryId
where !excludeTypes.Contains(account.AccountType)
where account.StateChangeDate == null ||
(account.StateChangeDate.Month - DateTime.Now.Month)
<= maxStateChangeMonth
where includeMortgage.Contains(account.AccountType) ||
account.AccountType.Contains("Mortgage")
where account.AccountStatusId != excludeStatusId
select account.MinimumInstallment);
string sqlQuery = (sum as ObjectQuery).ToTraceString();
Please note that this code will not perform the actual query, it is usable for testing purposes only.
Check out this article if you are interested in ready-for-production logging implementation.
There can be a performance difference:
The SQL query returns a single number (SELECT Sum...) directly from the database server to the client which executes the query.
In your LINQ query you have a greedy operator (.ToList()) in between:
var sum = (...
...
select account.MinimumInstallment).ToList()
.Sum(minimumInstallment =>
Math.Abs((decimal)(minimumInstallment)));
That means that the query on the SQL server does not contain the .Sum operation. The query returns a (potentially long?) list of MinimumInstallments. Then the .Sum operation is performed in memory on the client.
So effectively you switch from LINQ to Entities to LINQ to Objects after .ToList().
BTW: Can you check the last proposal in your previous question here which would avoid .ToList() on this query (if the proposal should work) and would therefore be closer to the SQL statement.
I can connect to a linked server with this:
SELECT testNo, soruTuruId, soruNo, cevap , degerlendirenTcNo, degerlendirilenTcNo
FROM OPENDATASOURCE('SQLOLEDB', 'Data Source=192.168.150.42;User ID=readerUser;Password=1').akreditasyon.dbo.tblPerfCevap
But I have to pass the password as parameter. and I try like this:
SET #connectionString = 'Data Source=192.168.150.42;User ID=readerUser;Password='+#pw
SELECT testNo, soruTuruId, soruNo, cevap , degerlendirenTcNo, degerlendirilenTcNo
FROM OPENDATASOURCE('SQLOLEDB', #connectionString ).akreditasyon.dbo.tblPerfCevap
and
SELECT testNo, soruTuruId, soruNo, cevap , degerlendirenTcNo, degerlendirilenTcNo
FROM OPENDATASOURCE('SQLOLEDB', 'Data Source=192.168.150.42;User ID=readerUser;Password='+#pw ).akreditasyon.dbo.tblPerfCevap
but didnt work:S
does anyone have an idea?
use exec () function to run the query. Wrap your query into a valid string.
Here's my working implementation of Ojulari's answer. I wanted the same stored proc to run from our Prod, QA, etc.. environment, each one needs to access a different BizTalk Server's database.
declare #DataSource varchar(100)
set #DataSource =
case
when dbo.GetEnvironment() = 'PROD' then 'Data Source=ProdBizTalkServer;UID=test;PWD=test'
when dbo.GetEnvironment() = 'QA' then 'Data Source=QABizTaklServer;UID=test;PWD=test'
ELSE null
end
declare #myExec varchar(max)
set #myExec = 'select
nvcMessageType,
COUNT(*)
from OpenDataSource(''SQLNCLI10'',''' + #DataSource + ''').BizTalkMsgBoxDb.dbo.Spool
where nvcMessageType like ''%#FlightMessageReceivedEvent''
group BY nvcMessageType
order by nvcMessageType
'
print '#myExec=' + IsNull(#myExec,'null')
EXEC(#myExec)