I need to generate a date range, based on the current date (or an input date). I can get the correct dates using VB, but I haven't worked out the TSQL Syntax for them yet. Can anyone tell me the TSQL syntax for manipulating dates in the following way...?
Start Date... This is the first day of the month, one year ago... in VB I worked it out as...
How do I subtract, say an integer from a datetime value. I tried to use the Convert function but wont work. All I want to do in my SP is subtract an integer from getdate() and do a query based on the result I get from that subtraction.
I've got a list of IDs seperated by commas and I want to get each indivdual ID and insert them into a table. Has anybody got any ideas how this can be done?
Hi all, I am a little weak at SQL, so bear with me. Can anyone give me an SP which uses "Between" to Display all Dates BETWEEN a fromDate and toDate??? Two conditions 1.Both Dates are stored as varchar. 2. I should be able to get the dates even if years are different, say between 20th December 2006 and 3rd January 2007 3.Is there a way to extract the yearDiff? Regards, Naveen
[I am new to asp.net] Assume I have a databse for "products"; product id is a primary key. Here is what I am trying to: 1. DetailsView for a product (eg id = 1110) (I got this far) 2. how can I list other products starting with 111x id 3. I also to show them on same page as 1110 as "parent" 111x as children Thanks,
I'm in the midst of a long file conversion job. Today I found that one of the tables (converted from csv) to be 6.7 million records. My sql script which I use to reconfigure the weird original date format, into something the rest of the planet uses, times out due to the size.
Does anyone please know of a file utility to automagically split sql server 2005 tables for later re-combining once my scripts have successfully completed their task on the smaller tables?
We've got an employee database that I'm modifying to include two photos of each employee, a small thumbnail image and a full-size image. The HR department maintenance page contains a listbox of employee names, which, when clicked, populates a detailsview control.To get the images to display and be updatable, I've had to structure the following SqlDatasource and DetailsView: 1 <asp:DetailsView ID="dvEmp" runat="server"2 AutoGenerateRows="false"3 DataSourceID="dsEmpView"4 DataKeyNames="empID">5 <Fields>6 <asp:CommandField ShowEditButton="true" ShowCancelButton="true" ShowInsertButton="true" />7 <asp:BoundField HeaderText="Name (Last, First)" DataField="empname" />8 <asp:TemplateField HeaderText="Thumbnail photo">9 <ItemTemplate>10 <asp:Image ID="imgThumbnail" runat="server" ImageUrl='<%# formatThumbURL(DataBinder.Eval(Container.DataItem,"empID")) %>' />11 </ItemTemplate>12 <EditItemTemplate>13 <asp:Image ID="imgThumbHidden" runat="server" ImageUrl='<%# Bind("thumbURL") %>' Visible="false" />14 <asp:FileUpload ID="upldThumbnail" runat="server" />15 </EditItemTemplate>16 </asp:TemplateField>17 <asp:TemplateField HeaderText="Full Photo">18 <ItemTemplate>19 <asp:Image ID="imgPhoto" runat="server" ImageUrl='<%# formatImageURL(DataBinder.Eval(Container.DataItem,"empID")) %>' />20 </ItemTemplate>21 <EditItemTemplate>22 <asp:Image ID="imgPhotoHidden" runat="server" ImageUrl='<%# Bind("photoURL") %>' Visible="false" />23 <asp:FileUpload ID="upldPhoto" runat="server" />24 </EditItemTemplate>25 </asp:TemplateField>26 </Fields>27 </asp:DetailsView>28 29 <asp:SqlDataSource ID="dsEmpView"30 runat="server"31 ConnectionString="<%$ ConnectionStrings:eSignInConnectionString %>"32 OnInserting="dsEmpView_Inserting"33 OnUpdating="dsEmpView_Updating"34 SelectCommand="SELECT empID, empname, photoURL, thumbURL FROM employees where (empID = @empID)"35 InsertCommand="INSERT INTO employees (empname, photoURL, thumbURL) values(@empname, @photoURL, @thumbURL)"36 UpdateCommand="UPDATE employees SET empname=@empname, photoURL=@photoURL, thumbURL=@thumbURL WHERE (empID = @empID)">37 <SelectParameters>38 <asp:ControlParameter ControlID="lbxEmps" Name="empID" PropertyName="SelectedValue" Type="Int16" />39 </SelectParameters>40 </asp:SqlDataSource>41 42 -----43 44 Protected Sub dsEmpView_Updating(ByVal sender As Object, ByVal e As SqlDataSourceCommandEventArgs)45 Dim bAbort As Boolean = False46 Dim bThumb(), bPhoto() As Byte47 If e.Command.Parameters("@ename").Value.trim = "" Then bAbort = True48 Dim imgT As FileUpload = CType(dvEmp.FindControl("upldThumbnail"), FileUpload)49 If imgT.HasFile Then50 Using reader As BinaryReader = New BinaryReader(imgT.PostedFile.InputStream)51 bThumb = reader.ReadBytes(imgT.PostedFile.ContentLength)52 e.Command.Parameters("@thumbURL").Value = bThumb53 End Using54 End If55 Dim imgP As FileUpload = CType(dvEmp.FindControl("upldPhoto"), FileUpload)56 If imgP.HasFile Then57 Using reader As BinaryReader = New BinaryReader(imgP.PostedFile.InputStream)58 bPhoto = reader.ReadBytes(imgP.PostedFile.ContentLength)59 e.Command.Parameters("@photoURL").Value = bPhoto60 End Using61 End If62 e.Cancel = bAbort63 End SubIf the user updates both images at the same time by populating their respective FileUpload boxes, everything works as advertized. But if the user only updates one image (or neither image), things break. If they upload, say, just the full-size photo during an update, then it gives the error "System.Data.SqlClient.SqlException: Operand type clash: nvarchar is incompatible with image".I think this error occurs because the update command is trying to set the parameter "thumbURL" without having any actual data to set. But since I really don't want this image updated with nothing, thereby erasingthe photo already in the database, I'd rather remove this parameter from the update string.So, let's remove the parameter that updates that image by adding the following code just after the "End Using" lines: Else Dim p As SqlClient.SqlParameter = New SqlClient.SqlParameter("@thumbURL", SqlDbType.Image) e.Command.Parameters.Remove(p) (Similar code goes into the code block that handles the photo upload)Running the same update without an image in the thumb fileupload box, I now get this error: "System.ArgumentException: Attempted to remove an SqlParameter that is not contained by this SqlParameterCollection."Huh? It's not there? Okay, so lets work it from the other end: let's remove all references to the thumbURL and photoURL from the dsEmpView datasource. We'll make its UpdateCommand = "UPDATE employees SET empname=@empname WHERE (empID = @empID)", and put code in the dsEmpView_Updating sub that adds the correct parameter to the update command, but only if the fileupload box has something in it. Therefore: If imgT.HasFile Then Using reader As BinaryReader = New BinaryReader(imgT.PostedFile.InputStream) bThumb = reader.ReadBytes(imgT.PostedFile.ContentLength) e.Command.Parameters.Add(New SqlClient.SqlParameter("@thumbURL", SqlDbType.Image, imgT.PostedFile.ContentLength)) e.Command.Parameters("@thumbURL").Value = bThumb End Using End If (Similar code goes into the code block that handles the photo upload)But reversing the angle of attack only reverses the error. Uploading only the photo and not the thumb image results in: "System.Data.SqlClient.SqlException: The variable name '@photoURL' has already been declared. Variable names must be unique within a query batch or stored procedure."So now it's telling me the parameter IS there, even though I just removed it.ARRRGH!What am I doing wrong, and more importantly, how can I fix it?Thanks in advance.
I would like to manipulate the string to pull out only the number value. There is always a space between the number and the "KB". Looked at replace but got stuck, any help appreciated.
In my database I have a table for Users, with an int primary key, and a table for Connections, with a combined primary key consisting of two UserID foreign keys. (the smallest first)
At the point I am stuck I have one UserID, lets call it current_user, and a column returned by a select statement consisting of UserIDs. Some of these IDs will likely be smaller than current_user, and some will likely be larger.
What i need to do is construct a view of two columns, combining each of the UserIDs in the column I have with current_user, with the smallest UserID of each pair residing in the first column, and the largest in the second column.
The point of this is to then SELECT the connections identified by the UserID pairs.
I suspect I could accomplish this if I could set individual fields in the a view, but I seem to have missed (or forgotten) that lecture. Anybody want to clue me in?
Hi, I'm having problems manipulating the results from multiple count(*) queries.
I have a table 'RECOMMENDATIONS' holding a field called 'SCORE'. This field holds a number from 1 to 10 and has no null or zero figures.
I currently have the following three queries: 1) SELECT COUNT(*) FROM RECOMMENDATIONS WHERE SCORE IN (1,2,3,4,5,6) 2) SELECT COUNT(*) FROM RECOMMENDATIONS WHERE SCORE IN (9,10) 3) SELECT COUNT(*) FROM RECOMMENDATIONS
I now need to combine these three queries so that i can divide and multiply the resulst: (query 2/query 1)*query 3
My initial idea was: SELECT (COUNT(*)/(SELECT COUNT(*) FROM RECOMMENDATIONS WHERE SCORE IN (1,2,3,4,5,6)))* (SELECT COUNT(*) FROM RECOMMENDATIONS) FROM RECOMMENDATIONS WHERE SCORE IN (9,10)
... but this gives a result of "0". I then stripped out the multiplication section to see if the divide was working: SELECT COUNT(*)/(SELECT COUNT(*) FROM RECOMMENDATIONS WHERE SCORE IN (1,2,3,4,5,6)) FROM RECOMMENDATIONS WHERE SCORE IN (9,10)
Hi I am new to SQL programming. This is what I am trying to do in store procedure. Alter a table - adding two columns. Then update those columns Both the above action in same procedure . When I execute them - it complains that the columns I am adding in the first part of store procedure , does not exists. So the SP looks like this create store procedure <name> as alter table <name> ADD column_1 nvarchar (256), column_2 nvarchar (256);
update table set column_1 = <condition> column_2 = <condition>
The SQL complains - invalid column name column_1 invalid column name column_2
Hi,I have one stored procedure that calls another ( EXEC proc_abcd ). I wouldlike to return a result set (a temporary table I have created in theprocedure proc_abcd) to the calling procedure for further manipulation. Howcan I do this given that TABLE variables cannot be passed into, or returnedfrom, a stored procedure?Thanks,RobinExample: (if such a thing were possible):DECLARE @myTempTable1 TABLE ( ID INT NOT NULL )DECLARE @myTempTable2 TABLE ( ID INT NOT NULL )...../*Insert a test value into the first temporary table*/INSERT INTO @myTempTable1 VALUES ( 1234 )...../*Execute a stored procedure returning another temporary table ofvalues.*/EXEC proc_abcd @myTempTable2 OUTPUT......../*Insert the values from the second temporary table into the first.*/SELECT * INTO @myTempTable1 FROM @myTempTable2
I am trying to find the best way to use the getDate() function in SQL Server CE to return a date and time which starts at midnight rather than the value of now which getDate() returns.
When running getDate I get the value of 29/04/2008 10:48:33 returned, but I want to return 29/04/2008 00:00:00 instead. The only way I can see to do this is like so:
Code Snippet
--SQL to get shifts for next 7 days. select * from SHIFTS
where STARTDATE between --Today at midnight 2008-04-29 00:00:00.000
A simple question I hope. I have got a textbox on a report and I'm trying to populate it by calling a custom assembly. I know I can reference it directly in the textbox (this works) but I am trying to do this from the code block. The following code didn't work:
Protected Overrides Sub OnInit() ReportItems!textbox2.Value = POCCustomAssembly.CustAssembly.Hello() End Sub
The TextBox is called textbox2 and the custom assembly simply returns a string.
I get an error message "The is an error on line 1 of custom code: [BC30469] Reference to a non-shared member requires an object reference".
I am having a problem writing a large amount of ntext data to a field within an ADO recordset. I am using the append chunk method but it does not seem to work. The SQL 7 field will hold the data its only about 60K.
I have to run a dynamic sql that i save in the database as a TEXT data type(due to a large size of the sql.) from a .NET app. Now i have to run this sql from the stored proc that returns the results back to .net app. I am running this dynamic sql with sp_executesql like this.. EXEC sp_executesql @Statement,N'@param1 varchar(3),@param2 varchar(1)',@param1,@param2,GO As i can't declare text,ntext etc variables in T-Sql(stored proc), so i am using this method in pulling the text type field "Statement". DECLARE @Statement varbinary(16)SELECT @Statement = TEXTPTR(Statement)FROM table1 READTEXT table1.statement @Statement 0 16566 So far so good, the issue is how to convert @Statment varbinary to nText to get it passed in sp_executesql. Note:- i can't use Exec to run the dynamic sql becuase i need to pass the params from the .net app and Exec proc doesn't take param from the stored proc from where it is called. I would appreciate if any body respond to this.
How can I do this with Parameters? I can get a single parameter to filter for a single date (or even a combo list of the dates in DB). But I want my parameters to interact so that they specify a range. Is this possible?
Today I have got one scenario to calculate the (sum of days difference minus(-) the dates if the same date is appearing both in assgn_dtm and complet_dtm)/* Here goes the table schema and sample data */
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[temp_tbl]') AND type in (N'U')) DROP TABLE [dbo].[temp_tbl] GO CREATE TABLE [dbo].[temp_tbl]( [tbl_id] [bigint] NULL, [cs_id] [int] NOT NULL, [USERID] [int] NOT NULL,
I have a table that has hotel guests and their start stay date and end stay date, i would like to insert into a new table the original information + add all days in between.
I want to know if there is a way to compare dates in the sql statement with dates that I input into a database and todays date. the datatype that I'm using is smalldatetime.The statement I used is:Select Date from Table where Date > 'Today.now'I get an errorCould this be done or is there another approach?
I have a table which records employees'time-off records. There are 6 columns in this TimeOff table. They are RequestID, EmpName, StartDate, EndDate, Type, NumofDays. I have another table which has all the dates from 01/01/1950 to 01/01/2056.
I am trying write a query which lists all the dates between the timeoff startdate and enddate, including the the start and end dates, but my query so far only lists the start and end date in a timeoff record:
SELECT D.[Date], Datename(dw,D.[Date]) AS Weekday FROM Dates D LEFT JOIN TimeOff T ON D.[Date] = T.OffStartDate OR D.[Date] = T.OffEndDate WHERE (OffType = 'Sick Day' AND EmpName = 'Cat White') AND (D.[Date] BETWEEN T.StartDate AND T.EndDate)
Has anyone ever written a function to retrieve all individual dates between two given dates? Using DATEDIFF I can get the number of days between two dates. However I need to iterate through the days to identify weekend and holiday dates. Has anyone ever written a function to do this?
So, if select datediff(d,'07/01/2007','07/15/2007') as NumOfDays returns 14, I'd need to iterate through the 14 days and get the weekends and holidays. Would I have to use a cursor to iterate through the days?
I'm trying to generate this query, that displays Budget Current Year , Actual Current Year and Prior Year Revenue. When It comes to the Budget and Actual everything works fine, however when I try to add the query for the Prior Year I get an error, and I realized that the leap date is causing the error
Here is what I'm trying to generate
InnCodeID Quarterly Monthly Days Period Year BARmRev AARmRev PYRmRev
ADDIS Q1 Jan 1 1 2008 NULL NULL
ADDIS Q1 Jan 1 1 2008 3462.14 5107.65
ADDIS Q1 Jan 1 1 2008 NULL NULL
ADDIS Q1 Jan 1 1 2008 NULL NULL
Here is the error that I'm getting:
Code Snippet
Msg 242, Level 16, State 3, Line 1
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
(4834 row(s) affected)
Here is my Transact-SQL Syntax (summarized because I Couldn't post it):
SELECT
(CASE WHEN (CASE WHEN dbo.Trans.Tr_Dept = '10' AND dbo.Trans.TR_Main = '5120' AND dbo.Trans.tR_sub = '01'
AND Year(dbo.Trans.TR_Date) = Year(dbo.CurrentDate.CurrDate) AND dbo.trans.Datatype = '1'
THEN dbo.trans.Tr_Amount ELSE NULL END) IS NOT NULL THEN
(SELECT Trans1.TR_Amount
FROM dbo.Trans Trans1
WHERE Trans1.TR_Dept = '10' AND TR_Main = '5120' AND TR_Sub = '01' AND trans1.TR_Date = CAST((CAST(Month(dbo.Trans.TR_Date)
AS varchar(2)) + '/' + CAST(Day(dbo.Trans.TR_Date) AS varchar(2)) + '/' + CAST(Year(dbo.CurrentDate.CurrDate) AS varchar(4))) AS datetime)
AND Trans1.TR_Entity = dbo.Trans.TR_Entity AND trans1.datatype = dbo.Trans.DataType) ELSE NULL END) * - 1 AS BARmRev,
--AA Script Here AS AARmRev,
(CASE WHEN (CASE WHEN dbo.Trans.Tr_Dept = '10' AND dbo.Trans.TR_Main = '5120' AND dbo.Trans.tR_sub = '01' AND Year(dbo.Trans.TR_Date)
= Year(dbo.CurrentDate.CurrDate) AND dbo.trans.Datatype = '1' THEN dbo.trans.Tr_Amount ELSE NULL END) IS NOT NULL THEN
(SELECT SUM(Trans1.TR_Amount)
FROM dbo.Trans Trans1
WHERE RIGHT(RTRIM(Trans1.TR_Dept), 2) = '10' AND Trans1.TR_Main = '5120' AND Trans1.TR_Sub NOT BETWEEN '04' AND '05' AND
trans1.TR_Date = CAST((CAST(Month(dbo.Trans.TR_Date) AS varchar(2)) + '/' + CAST(Day(dbo.Trans.TR_Date) AS varchar(2))
+ '/' + CAST(Year(dbo.CurrentDate.CurrDate)-1 AS varchar(4))) AS datetime) AND Trans1.TR_Entity = dbo.Trans.TR_Entity AND
Hello All, I am trying to Add certain number of days to a particular date. and my requirement is that it need to exclude all saturdays and sundays and then give me the resultant date in Sqlserver. Please can anyone help me in achieving it. thanks Shiva Kumar
Hi can anyone help me , or am I on the wrong track.
Is there any easy way to create a stored procedure that inserts into a table the relevant months dates into a table based on the month and year as parameters. I.e say the parameters passed are 01/2001 hence based on this all of the month of January 2001 dates are inserted into a table in this format : 'Jan 01 2001 12:00:00'
We are deploying a system in the UK in SQL Server 6.5. They want the date to default to dd/mm/yy. Is there a way to set this on a permanent basis? Is there a way to set the server so any time a date is display, including getdate(), the result is dd/mm/yy?
I have a table which contains apart from other fields, 2 dates. i.e. startdate and enddate.
The startdate is always less than / equal to enddate.
I want to write a stored proc where I will give a date as a parameter and it should give me all the records there my date is between the startdate and the enddate.
Also I want to create a temp table in the procedure and the table gets populated with all the dates that comes between startdate and enddate, both dates inclusive.
I know this might be a tall order, but I am new to writing stored procedure, so I will be obliged if somebody can help me out
I have an assignment using SQL this is the first time i have used it but i can understand the basics.
It is for an instrument service company and i need to find what instruments have not been serviced for a year. i already know i have to:
SELECT instrument number, date of last service FROM Instrument table
but after this i am unsure what code i can use in order to find all instruments that have not been servided in over 365 days what code can is best to use?