ASP.NET query substring - asp.net

I've got this field in my database year_start_1 and it is an integer field and an example of an ouput is 20100827 I'm trying to create a substring to create year, week, day and change the format to be 27/08/2010
Here's what i'm trying
Dim query as String = "Select * from openquery (devbook, 'SELECT cast(year_start_1 as varchar(8)) as year_start_1, DATENAME(DAY, substring(CAST(year_start_1 AS VARCHAR(8)),6,2) + DATENAME(MONTH, substring(CAST(year_start_1 AS VARCHAR(8)),4,2) + DATENAME(YEAR, substring(CAST(year_start_1 AS VARCHAR(8)),1,4))) FROM web_statements')"
It's just throwing up an error and I not sure why:
Server was unable to process request
I have tried using convert but it doesn't work.
Any ideas?
UPDATE
with Chris's suggestion
Dim query as String = "Select * from openquery (devbook, 'SELECT year_start_1, cast(year_start_1 as varchar(8)) as year_start_1, substring(CAST(year_start_1 AS VARCHAR(8)),7,2)+''/''+substring(CAST(year_start_1 AS VARCHAR(8)),5,2)+''/''+substring(CAST(year_start_1 AS VARCHAR(8)),1,4) FROM web_statements')"
Still getting the error
Thanks
UPDATE
Couldn't seem to get it to work within the query so had to do a work around in the ASP.Net code
'POINTS END DATE YEAR
Dim strPointsDateEndYear = Mid(drv.Row("year_end_1"), 3, 2)
Dim strPointsDateEndMonth = Mid(drv.Row("year_end_1"), 5,2)
Dim strPointsDateEndDay = Right(drv.Row("year_end_1"), 2)
Dim strPointsDateEnd As String = strPointsDateEndDay + "/" + strPointsDateEndMonth + "/" + strPointsDateEndYear
Thanks for the help though

Your first DATENAME doesn't seem to close all its brackets before the next DATENAME starts:
DATENAME(DAY, substring(CAST(year_start_1 AS VARCHAR(8)),6,2) + DATENAME[...]
Should I assume be:
DATENAME(DAY, substring(CAST(year_start_1 AS VARCHAR(8)),6,2)) + DATENAME[...]
Edit: Though having fixed that minor error (and converted it to debug) I'm getting errors about casting strings to dates. I'm not sure what the datename stuff is meant to do but how about this:
DECLARE #year_start_1 int
SET #year_start_1 = 20100827
SELECT cast(#year_start_1 as varchar(8)) as year_start_1,
substring(CAST(#year_start_1 AS VARCHAR(8)),7,2)+'/'+substring(CAST(#year_start_1 AS VARCHAR(8)),5,2)+'/'+substring(CAST(#year_start_1 AS VARCHAR(8)),1,4)
(converted to a non table based select for test/debug purposes)
So what you would want for your final line of sql would be (untested):
Select * from openquery (devbook, 'SELECT cast(year_start_1 as varchar(8)) as year_start_1, substring(CAST(year_start_1 AS VARCHAR(8)),7,2)+'/'+substring(CAST(year_start_1 AS VARCHAR(8)),5,2)+'/'+substring(CAST(year_start_1 AS VARCHAR(8)),1,4) FROM web_statements')
Second Edit for debug notes:
I thought it might also be worth suggesting how to debug this sort of problem. The error message suggested that the linked server you were sending the sub-statement to was unable to process the request. The first thing to try in this case would be to run the request directly on the server to see what happens. In this case in fact just parsing it on its own would have revealed the first errors I got.
Once you have your statement running form management studio or whatever directly on the server you can try converting it back into the "openquery" style statement and see if ti still works. Bascially break down your complicated scenario into lots of smaller bits to test each one individually.

select convert(varchar(10),convert(smalldatetime,'20100827'),103) will return 08/27/2010
so, your solution is:
select convert(varchar(10),convert(smalldatetime,convert(varchar,year_start_1)),103) will return 27/08/2010

You are using the datename function on strings, but it should be used on a datetime value. They are nested inside each other so you would end up with just the day, and besided it doesn't even do what you are looking for.
To get the format that you asked for, you can just use string operations to split it up in it's components and add slashes between them:
substring(CAST(year_start_1 AS VARCHAR(8)),7,2) + '/' +
substring(CAST(year_start_1 AS VARCHAR(8)),5,2) + '/' +
substring(CAST(year_start_1 AS VARCHAR(8)),1,4)

Related

Using Variable in the query

I'm struggling to make these two lines work without error.
campaignName = result['campaign_name']
db_conn.execute('INSERT INTO Report (CAMPAIGN) VALUES ("' + campaignName + '")')
I thought that the "'" in "result['campaign_name']" was the problem but even if I assigned the variable the error is persistent.
The error:
Thank you,
EDIT: I've modified my request to:
db_conn.execute("INSERT INTO Report (CAMPAIGN) VALUES ('" + str(campaignName.encode()) + "')")
And the script stops at the first dash "-".
I solved the problem this way:
db_conn.execute("INSERT INTO Report (CAMPAIGN) VALUES (?)", (campaignName,))

Arithmetic overflow error converting expression to data type datetime. in asp.net

This is my code
sqlquery = "select * from Mytables where cname='" + name + "' and cast(cast('" + txtselectdate.Text + "' as char(8)) as datetime)";
Getting error as Arithmetic overflow error converting expression to data type datetime.
Please suggest some ideas
Use tihs
CONVERT(Datetime,txtselectdate.Text,110)
You can use any format instead of 110
or
you can simply pass the converted date in your query like this
DateTime.Parse(txtselectdate.Text)
then you do not need to cast it in query.
===========Update ========
select * from mytable where cname='" + name + "' and yourcolumnname=CONVERT(Datetime,'" + txtselectdate.Text + "',110)"
Add column name in your query by which this textbox value will match.
Hai all thanks for the help I got the answer it was a datatype problem in my database
I havent saved the data type as datetime so they occurs a clash in updating previously it was nvarchar

Return an integer if nothing is found (TSQL ASP.NET VB)

I need to return a value (0) if nothing is found in an SQL call.
Here is what i have (edited/simplified to make more sense out of context), this is baing called from the codebehind.
sql1 = "INSERT INTO [Xtr_MenuItems]([menu_order])
values(1 + (select max(menu_order) from [Xtr_MenuItems]))
SO into database i insert the max number found in [menu_order] + 1. this works fine, assuming something is found.
However, if (select max(menu_order) from [Xtr_MenuItems])) fails (nothing found) then i want to return 0 (as 1 + nothing = nothing, and sql explodes)
How can i do this? I have tried 'IF EXISTS', 'OUTPUT' in various ways but cant get it to work...
Try this:
sql1 = "INSERT INTO [Xtr_MenuItems]([menu_order])
values(1 + ISNULL((select max(menu_order) from [Xtr_MenuItems]),0))
I used ISNULL function where if the result of query is null returns 0
Instead of values, you could use select straight away:
insert Xtr_MenuItems
(menu_order)
select 1 + isnull(max(menu_order),0)
from Xtr_MenuItems
COALESCE is the standards compliant way to provides alternatives for null values:
sql1 = "INSERT INTO [Xtr_MenuItems]([menu_order])
values(1 + COALESCE((select max(menu_order) from [Xtr_MenuItems]),0))
It has similar syntax to the ISNULL function provided by Microsoft, but will work across multiple db platforms and can handle multiple fallbacks.
W3Schools privides a great introduction to null handling here.

Npgsql count rows error

The code I have a problem with:
NpgsqlCommand if_ex = new NpgsqlCommand("SELECT count(id_unit) FROM unit WHERE name=" + "'" + tmp + "'", conn);
int ex = (int)if_ex.ExecuteScalar();
Throws an exception:
Specified cast is not valid.
I am trying to get the row count of columns that have the same name (the string that I pass)
i know I should use parameters, but at this point I am only testing a few things so I figured might as well just do it like this for now.
This problem happens because the return type of a query like: select count(*) is an long and not an int. If you change your code to long ex = (long)if_ex.ExecuteScalar(); you will get what you want. I hope it helps.

VBScript - Database - Recordset - How to pass DateDiff value in the database

I'm using DateDiff() function of ASP to find the date difference between two dates.
The Function works fine and displays the exact date difference between two dates but when it comes to insert this value in the database it takes 9 as the value irrespect of any date difference.
Suppose difference between two dates is more than 15 or 20 days, in the database it takes "9".
I have used INT as the DATA TYPE for the column where it displaying the date difference.
Is DATA TYPE creating an issue here?
I even tried using session variable to store the value but no luck - here's my code below:
if request.Form("sub") <> "" then
sql = "Select * from emp_leave_details"
rs.open sql , con, 1, 2
dim diff
dim todate
dim fromdate
fromdate= rs("leave_from")
todate= rs("leave_to")
session("date_diff")=datediff("d",fromdate,todate)
rs.addnew
rs("emp_name") = request.Form("name")
rs("emp_no") = request.Form("number")
rs("address") = request.Form("address")
rs("contact_no") = request.Form("contact")
rs("mobile_no") = request.Form("mobile")
rs("contact_onleave") = request.Form("contact_details")
rs("leave_type") = request.Form("rad")
rs("other_leave_details") = request.Form("PS")
rs("leave_from") = request.Form("from")
rs("leave_to") = request.Form("to")
rs("applied_by") = request.Form("apply")
rs("accepted_by") = request.Form("accept")
rs("approved_by") = request.Form("approve")
rs("no_of_leave_taken")= session("date_diff")
rs.update
response.Write("<script language='javascript'>{update();}</script>")
rs.close
end if
The datatype has nothing to do with this. Storing the value in the session is not the solution. You can use a regular variable.
From your code it looks like you always use the same values for fromdate and todate. This is because you do not iterate the rows in the resultset.
if not rs.bof and not rs.eof then
do while not rs.eof
'' code to execute for each row
rs.moveNext
loop
end if
In your current script rs will always return the results of the first row returned by the query.
The second problem your running into might be the Date datatype. Convert your value to a date using cDate and use this to calculate the difference.
Your problem is , you search for "Select * from emp_leave_details" which always gives all records from that table. You retrieve the values of the first record and do a diff of these, which results in always the same value, that is normal. From your question it is unclear what you really want to do. I suppose so want so select a record like
Select * from emp_leave_details where emp_name=<%=request.Form("name")%>
and based on that add a new record with a computed no_of_leave_taken.
Sorry guys my bad...
It was the database field name that I was calling instead of
fromdate= request.form("from")
todate= request.form("to")
I was calling this
fromdate= request.form("leave_from")
todate= request.form("leave_to")
Sorry again..but I really appreciate you all for providing me with all that possible solutions.
Thanks.

Resources