Transact SQL :: Date Loop Returning Min And Max Datetimestamp

Oct 21, 2015

I have a requirement for the following query which uses a timestamp data type field

[eventdate]Select field1, fileds2, filed3, {min(eventdate) as max(eventdate) per day/date} from sometable

View 4 Replies


ADVERTISEMENT

Transact SQL :: Loop A Month In A Specified Date Range?

Jul 23, 2015

I am trying to query a code where i need to loop a month in a specified date range. Inside the loop I need to return a result of data each month and need to update the table of the returned data. How do I do the update a field inside the loop? Here's my query:

declare @table1 table (
YEAR_EFF int,
MONTH_EFF int,
IDNumber (8),
SUBS_CNT smallint,
MEM_CNT smallint)
declare @StartDate datetime,

[code]....

Others says I need to use exec sp_executesql N'' but how do I use it using my code above?

View 7 Replies View Related

Transact SQL :: Load Data For Last 15 Days By Decrementing Current Date And While Loop

Sep 21, 2015

I have a dynamic sql query where in I am comparing two tables and loading data for last 15 days. e.g today 2050921 then I am going to load till 20150906.

I pass on 2 variables @currentdate and @currentdate-1 to the query which are in date format 'yyyymmdd'

I need to do this for last 15 days how do I do this using while loop.

Note my date format is YYYYMMDD.

DECLARE @SQL VARCHAR(MAX)
@sql = ' insert into target 
select from table_1_currentdate a
LEFT JOIN Table_2_currentdate-1 b
on a.col1=b.col1  where b.col1 is null '

exec(@sql)

I have to use while loop and decrement it every time and load data for last 15 days comparing two tables. I tried so many times I am not getting it right .

View 3 Replies View Related

Transact SQL :: Split Date Range Into Monthly Wise And Loop Through Each Month To Perform Some Operation

Oct 20, 2015

Let's say if the date is 01/01/2015 till 01/01/2016

I want split these dates monthly format wise and then use them in variable in cursors to loop

For an example Monthly date should be 01/01/2015 and 01/31/2015 and use these two values in 2 variables and make a loop until it never ends whole date range which is 01/01/2016

View 2 Replies View Related

Datetimestamp Into Db

May 6, 2007

as you can see i am trying to figure out how to get the users IP address and a datetimestamp into my db. can anyone assist. i tried to comment out the datetimestamp but the iprequest does not work either.
The site i am workingon is papertrailinvites.com the newsleter on the left hand side there. i am trying to collect the email address, ip address and a datetimestamp. inserting the email address works now i just need to get the ipaddress and the datetimestamp in the db
code is below
Thanks 
 
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["cardsConnectionString1"].ConnectionString)) {
String newemail = Newsletter_Email.Text;
 
SqlCommand cmd = new SqlCommand("INSERT INTO Email (EmailAddress, IPAddress, DateTimeStamp) Values (@EmailAddress, @IPAddress, @DateTimeStamp)", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@EmailAddRess", newemail);
cmd.Parameters.AddWithValue("@IPAddress", HttpContext.Current.Request.UserHostAddress);
//cmd.Parameters.AddWithValue("@DateTimeStamp",
conn.Open();
cmd.ExecuteNonQuery();
 
 

View 1 Replies View Related

Problems Inserting DateTimeStamp Into Database

Sep 26, 2006

Here's the error I get trying to run the code posted below..."Prepared statement '(@datestamp datetime,@PrevValue real,@NewValue real,@IPaddress r' expects parameter @datestamp, which was not supplied."I've tried it without the quotes around the DateTime.Now and also adding the # around them.  Without the quotes, I do get a different error because it doesn't like the spaces in the DateTime text.  Also, the datestamp data in the database is formatted as a datetime (MS SQL Server 2005).Here's my code:Private Sub UpdateRefresh()UpdateConnection.Open()UpdateDataAdapter.InsertCommand.CommandText = "INSERT INTO dbo.tbDeploy(datestamp," & _"PrevValue, NewValue, IPaddress, HighCapability, LowCapability, Share) VALUES" & _"('" & DateTime.Now & "', '" & lblCurrent.Text & "', '" & lblCurrent.Text & _"', '" & lblIP.Text & "', '" & lblHigh.Text & "', '" & lblLow.Text & "', '" & lblShare.Text & "')"UpdateDataAdapter.InsertCommand.ExecuteNonQuery()UpdateConnection.Close()End Sub

View 1 Replies View Related

Derived Column - DateTimeStamp From String (dd-mmm-yy)

Jun 7, 2006

I have come across something strange. I was wondering anyone else had the same problem or is it me?

I have a source file as shown below:
1,30-Feb-06,3,Test
2,20-Feb-06,5,Test1

Second column is defined as String(9) in the flat file source. Then I have a Derived Column between source and Trash destination. The Derived Column adds a new column to the datd flow. The expression is as shown below :
(DT_DBTIMESTAMP)(SUBSTRING(Col2,1,2) + "/" + SUBSTRING(Col2,4,3) + "/" + SUBSTRING(Col2,8,2))

The data is loading into the database successfully, where I was expecting it to fail. I placed a data viewer and saw the following result set.

Source (Col2) Derived Col
------------------- ------------------
30-Feb-06 06/02/1930 00:00:00 - WRONG result set
20-Feb-06 20/02/2006 00:00:00 - RIGHT result set

Can anyone repeat this problem or am I missing something? I have got SP1 and Hotfix installed.

Thanks

Sutha

View 1 Replies View Related

PL-SQL LOOP Equivilant In TRANSACT-SQL

Jul 20, 2005

Hi,I need to convert this anonymous pl-sql block into transact-sql to runin Microsoft SQL Server Query Analyser.Does anyone know what the conversion syntax would be?I know that to declare variables to use the @.PRINT for printing the output.No idea for the LOOP.Any suggestions greatly appreciated.Many thanks.Thiko!____________________________________________SET SERVEROUTPUT ONDECLARErecordcount NUMBER;BEGINDBMS_OUTPUT.ENABLE(5000000); -- Sets buffer size.recordcount := 0;LOOPINSERT INTO RecoverTest VALUES (SYSDATE - (recordcount / 4));COMMIT; -- frees up rollback segment;recordcount := recordcount + 1;DBMS_OUTPUT.PUT_LINE('INSERT: ' || recordcount || ' - 45000 ');EXIT WHEN recordcount > 45000;END LOOP;END;/

View 1 Replies View Related

Transact SQL :: Returning A Response From XML-based Web Service

Aug 18, 2015

I'm running into an interesting issue when returning a response from an XML-based web service. The following code returns good values from PRINT

@response
DECLARE @address varchar(50) = '90210'
DECLARE @URL varchar(MAX)
SET @URL = 'https://somewebsite/map.xml?zip=' +
CASE WHEN @Address IS NOT NULL THEN @Address ELSE '' END
SET @URL = REPLACE(@URL, ' ', '+')

[code]...

However, on some calls to the web service, the value returned is longer than 4000 characters. In these instances, it appears as though it breaks the whole thing and returns nothing. However, if I change the @Response parameter to nvarchar(max), it never returns anything, even on responses that are shorter than 4000 characters. what the fundamental difference is here between nvarchar(4000) and nvarchar(max) with respects to how it stores responseText. More importantly, how to get this to return a value even when it exceeds 4,000 characters?

View 2 Replies View Related

Transact SQL :: Returning Specific Characters After Space?

Jul 6, 2015

I have a column that has data in column user4 such as :

CALBRIG  ALBION COMPANY LTD  
1900 No. 8 Road, RIchmond, BC, V6V 1W3

I can do a LEFT(user4, 7) That returns me the first 7 charcters but I need to retrieve the company information but the number of characters may vary with each field. Is there anyway I can do this without returning the entire line?

View 3 Replies View Related

Transact SQL :: GetDate Function Not Returning Any Results?

May 27, 2015

I am having a problem with the GETDATE().

WHERE TableName.ColumnNamne = Getdate()

The above SQL function does not return any results whereas the below SQL code returns results. Am I doing anything wrong?

WHERE SalesOrder.New_ActualShipmentDate >= GETDATE()

View 35 Replies View Related

Transact SQL :: Pass Filenames To A Loop

Aug 27, 2015

I’m working on building a file list from a directory I have and wish to loop through the filenames. I’ve worked out I can get the list using

EXEC
xp_dirtree @path, 10, 1

I’m just not sure out I pass this to my loop 1 element at a time.

E.g. Let’s say there are 10 files in my folder, I wish to loop through each name using my @Filename parameter

DECLARE @Path
varchar(50), @FileName
varchar(20)
SET @Path
= 'C:myFiles'
EXEC
xp_dirtree @path, 10, 1

[Code] ....

View 5 Replies View Related

Transact SQL :: Loop Though Row And Populate Missing Row

Oct 8, 2015

Col1 to Col9 represent the account information, Col10 amount, Col 11 represents the month and  Col12 represents year. According to the data there wasn't any activity for the month 1, 2 and 3.

Col1
Col2
Col3
Col4
Col5
Col6
Col7
Col8
Col9
Col10
Col11
Col12

[code]....

View 3 Replies View Related

Transact SQL :: How To Update Table Without Using While Loop

Nov 15, 2015

I have two tables i have to update table2 using table1 without using while loop.

example given below.

Table1 

rid
id
amt
firdate
lastdate

1
1
500

[code]....

View 7 Replies View Related

Transact SQL :: Can Pass A Variable Value Out While Loop

Nov 3, 2015

-- Create an Employee table.

CREATE TABLE dbo.MyEmployees
(
EmployeeID smallint NOT NULL,
FirstName nvarchar(30)  NOT NULL,
LastName  nvarchar(40) NOT NULL,
Title nvarchar(50) NOT NULL,
DeptID smallint NOT NULL,
ManagerID int NULL,
 CONSTRAINT PK_EmployeeID PRIMARY KEY CLUSTERED (EmployeeID ASC) 
);

-- Populate the table with values.

INSERT INTO dbo.MyEmployees VALUES 
 (1, N'Ken', N'Sánchez', N'Chief Executive Officer',16,NULL)
,(273, N'Brian', N'Welcker', N'Vice President of Sales',3,1)
,(274, N'Stephen', N'Jiang', N'North American Sales Manager',3,273)
,(275, N'Michael', N'Blythe', N'Sales Representative',3,274)

[code]....

View 3 Replies View Related

Transact SQL :: Returning Different Data When Part Of Query Is Separate?

Aug 3, 2015

I am writing a stored procedure to prepare some reports.

The issue is that I am summing up the combined bid, 'QuoteTotal' + Sum(InvoiceItemAmount) (eg, quote add ons).

When part of the larger query it returns a different, and incorrect amount. The query listed after the main query is just that line and it's appropriate parts and it returns the correct amount. What can I do to correct this and where lies the problem so I can learn from this situation?

alter PROCEDURE [dbo].[Select_Quote_Info_By_Salesmen_By_Status]
@Salesmen nvarchar(50),
@QuoteStatus nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;

[code]...

View 5 Replies View Related

Transact SQL :: Insert Trigger Returning Incorrect Results

Jul 11, 2015

SQL Version:  SQL2014

PROBLEM:  The SQL insert trigger code below is returning incorrect results.  In some cases the results returned are from entirely different fields than those specified as the source field in the SET statement.  For instance the value returne for the Price_BeforeAdj field does not = 20000000?  It returns a NULL.  See code below.

OFFENDING CODE:

ALTER TRIGGER [dbo].[xcti_WIPAdjustments_I]
   ON  [dbo].[budxcWIPAdjustments]
AFTER INSERT AS
BEGIN
 SET NOCOUNT ON;
  UPDATE budxcWIPAdjustments

[Code] ....

View 11 Replies View Related

Transact SQL :: Loop - How To Get Data For Each Of Active Users

Jun 9, 2015

My insert statement for #Data - I only need to process each @EmployeeID one time, which is why I thought a loop would be sufficient, but I let this process run for 2 hrs and it still had not completed, so I feel I must have set-up something incorrectly!

This is my syntax, I am creating a table of active users, then wanting to get data for each of those active users.  But only get the data for each active user 1 time.

Declare @EmployeeID varchar(50)
CREATE TABLE #ActiveUsers
(
ID INT IDENTITY NOT NULL
,EmployeeID varchar(50)
,processed int
)
Create Table #Data

[Code] ....

View 5 Replies View Related

Transact SQL :: How To Add Columns To Temporary Table In Loop

Aug 27, 2015

How to add columns to temporary table in loop with sample code.

View 12 Replies View Related

Transact SQL :: Passing Value In Where Condition Loop Wise

Jun 1, 2015

I want to calculate year to month data for month wise . Ihave start range and end range table like below

Start range and end range table

Start dateEnd date
01-04-201401-11-2014
01-04-201401-12-2014
01-04-201401-01-2015
01-04-201401-02-2015

[Code] ....

Then I want to pass this value one by one in below table for get value month wise

Main table

Branchamountperiod
Branch110201103
Branch22201104
Branch33201401
Branch44201402
Branch58201403
Branch610201404

[Code] ....

The below query is for november month: (Apr to Nov)

select * from maintable
where period between '01-04-2014' and '01-11-2014'
then for December month : (Apr to Dec)

So I want to pass second row

select * from maintable
where period between '01-04-2014' and '01-12-2014'
.....
....
select * from maintable
where period between '01-04-2015' and '01-12-2015'

Like wise I want to get month wise data of YTM data.

My expected output is

201411
201412
201501
201502
201503
201504
201505

[Code] ....

View 10 Replies View Related

Transact SQL :: While Loop Does Not End When Condition Is No Longer True

Dec 1, 2015

I have a Stored Procedure, wherein I need to use a while loop. essentially the loop looks like this.

Set @Kount = 1
--TestScript
Select 'TempReqTable', * from @TempReq
WHILE Exists(Select * from @TempReq WHERE TempID = @Kount)
BEGIN
--Do stuff with values from table
Set @Kount += 1
END

The test script confirms that there is only one row in the @TempReq table.  However the loop never stops running and @Kount keeps being incremented and incremented until I manually stop the execution of the SP.

Is there some rule that I am not aware of that does not allow the use of an Exists statement in the condition of a While loop?

View 12 Replies View Related

Returning First Or Last Date

Mar 18, 2015

creating a report in "Trac" using SQL. Basically we have a database running in Trac that manages a workflow, and goes through various stages Eg In Work, Review, etc. Now the nature of this means jobs can go in and out of the same state more than once. Therefore in my report I need to be able to return either the first date (or the last date) for any given state.

For example, when work is started it goes into Initial Layout during this phase of the design it can go on and off hold, so when I produce a report for metrics I want to see only the first time it went into the state Initial Layout. Similar example for Layout Approval, but in this instance I would want the last recorded date it went into this state.At the moment my report is returning multiple lines for the same "ticket" entry in the database, as it is listing each occurance any of the fields change.

Here's my code:

select
t.id as ticket,
t.type as type,
a.value as Project_site,
t.component as Layout_Site,
(CASE WHEN b.value ISNULL THEN ' ' ELSE b.value END) as Project,

[code]..

View 5 Replies View Related

Transact SQL :: Returning Multiple Values From Column In Select Statement?

Nov 26, 2015

I am writing a query and have the bulk of it already written. 

I am looking at a table that contains customer orders. There is a column named Customer_Order.Status Available values for this column is R, F, H, and C.

I'd like for my query to return all lines that have the value R, F, H.

My where clause is written like this 

WHERE CUSTOMER_ORDER.SITE_ID = 'XXX' AND CUSTOMER_ORDER.STATUS = ('R','H','F')

I know I'm missing something....

View 3 Replies View Related

Transact SQL :: Stored Procedure Not Returning Dataset (No Columns Are Coming)

Jun 3, 2015

We are facing an issue while executing a stored procedure which uses a table of current database with INNER JOIN a table of another database in same instance.

Per our requirement, we are inserting select statement output in table variable. Then applying business logic and finally showing the data from table variable.

This scenario is working exactly fine in Dev environment. But when we deployed the code in quality environment. Stored procedure does not returning OUTPUT/ (No column names) from table variable.

During initial investigation, we found that collation of these two databases are different but we added DATABASE_DEFAULT collation in the JOIN.

View 14 Replies View Related

Transact SQL :: Creating Stored Procedure With Cursor Loop

Sep 18, 2015

I appear to be having an issue where the @LetterVal and @Numeric variables aren't resetting for each loop iteration, so if no results are found, it just returns the previous loops values since they aren't overwritten.  Below is the stored procedure I've created:

ALTER PROCEDURE [dbo].[ap_CalcGrade] 
-- Add the parameters for the stored procedure here
@studId int,
@secId int,
@grdTyCd char(2),
@grdCdOcc int,
@Numeric int output,

[Code] ....

And below is the "test query" I'm using: 

--  *** Test Program ***
Declare @LetterVal varchar(2), -- Letter Grade
        @Numeric   int,        -- Numeric Grade
        @Result    int         -- Procedure Status (0 = OK) 
Execute @Result = dbo.ap_CalcGrade 102, 86, 'QZ', 3, 

[Code] ....

This is resulting in an output of: 

A+ 97
A+ 97
C- 72

but it should be returning the output below due to the 2nd data set not being valid/found in the sp query:
 
A+ 97
No Find
C- 72

I'm sure this is sloppy and not the most efficient way of doing this, so whats causing the errant results, and if there is any better way I should be writing it.  Below is the assignment requirements:

Create a stored procedure using the STUDENT database called ap_CalcGrade that does the following:

1. Accepts as input STUDENT_ID, SECTION_ID, GRADE_TYPE_CODE, and GRADE_CODE_OCCURRENCE
2. Outputs the numeric grade and the letter grade back to the user
3. If the numeric grade is found, return 0, otherwise return 1
4. You must use a cursor to loop through the GRADE_CONVERSION table to find the letter grade

View 6 Replies View Related

Transact SQL :: Loop On Rows - Count Of Documents For Each Supplier

Mar 22, 2015

I have 3 tables: Suppliers, Documents and Verification, each document may have multiple verification where I need to get the last verification according to verification date. So I just need a "Select top 1 result from Documents, Verification where doc_iddoc=ver_iddoc and result='True' order by ver_date desc" so far I get the result of the last verification, but here's the problem:

I need to get a row with the count of documents for each supplier, I mean:

Supplier Name     Docs      NegativeVerification
Acme Co                10                     1

that is I would need to loop for each supplier and each document and get the last verification, if one of any of documents have negative verification then add it to negative results. Is it possible to achieve this with a query or do I have to do it through stored procedure?

View 11 Replies View Related

Transact SQL :: Single Records - Loop To Only Insert Sum Total Of Each Day

Apr 22, 2015

I have the following query:

BEGIN TRAN

Declare @StartDt date = '2015-03-15'
Declare @EndDt date = DATEADD(M, 1, @StartDt)
declare @Days int = DATEDIFF(d, @StartDt, @EndDt)
declare @TBLSales as table(SaleDate date, Value money)
DECLARE @Today date
declare @TBLSalesCounts as table( StatusDesc varchar(100), Value money)

[Code] ....

I end up with the following result :

How would I alter my while loop to only insert the sum total of each day, instead of creating duplicates for each day.

E.g.
2015-04-22
1150.00
2015-04-21
 785.00
2015-04-20
 750.00

View 3 Replies View Related

SQL Server 2014 :: Insert Stored Procedure Output To Table And Add Datetimestamp

Jun 22, 2015

I have a need to insert stored procedure output a table and in addition to that add a datetimestamp column.. For example, Below is the process to get sp_who output into Table_Test table. But I want to add one additional column in Table_test table with datetimestamp when the procedure was executed.

insert into Table_Test execute sp_who

View 2 Replies View Related

Transact SQL :: Store Resultsets Of Stored Procedure Returning More Than One Resultset In Two Different Table?

Apr 20, 2015

I have on stored procedure which returns mote than one resultset i want that to store in two different temp table how can achieve this in SQL server.

Following is the stored procedure and table that i need to create.

create procedure GetData as begin select * from Empselect * from Deptend 
create table #tmp1 (Ddeptid int, deptname varchar(500),Location varchar(100))
Insert into #tmp1 (Ddeptid , deptname ,Location )
exec GetData

create table #tmp (empid int , ename varchar(500),DeptId int , salary int)
Insert into #tmp (empId,ename,deptId,salary)
exec GetData

View 9 Replies View Related

Transact SQL :: CASE With Subselect And DATEADD Function Returning NULL Values

Jun 15, 2015

I'm running the following test query on a single table:

SELECT sph.datestamp, sph.stocksymbol, sph.closing, DATENAME(dw, sph.datestamp),
CASE DATENAME(dw, sph.datestamp)    
WHEN 'Monday' then 'Monday'  
ELSE (SELECT CAST(sph2.datestamp AS nvarchar) FROM BI_Test.dbo.StockDB AS sph2 WHERE sph2.DateStamp = DATEADD(d, -1, sph.datestamp) AND sph2.StockSymbol = 'NYA') 
END AS TestCase,

[Code] ....

And here's an example of the output I'm getting:

Why the exact same subquery in the THEN of the second CASE statement is returning NULL when the first one completes as expected?

View 7 Replies View Related

Transact SQL :: Convert Server Date MM/DD/CCYY To Oracle Date Formatted As NUMBER (8,0)

Apr 30, 2015

So I have to build dynamic T-SQL because of a date parameter that will be provided. The Date Parameter will be provided in SSRS in normal MM/DD/CCYY format. So how do I then convert that date to my Oracle format

NUMERIC(8,0) CCYYMMDD?

I tried this...

SET@SQLQuery=@SQLQuery+'ANDMEMBER_SPAN.YMDEFF<='''''+CAST(@AsOfDateASVARCHAR)+''''''+@NewLineChar;
SET@SQLQuery=@SQLQuery+'ANDMEMBER_SPAN.YMDEFF>='''''+CAST(@AsOfDateASVARCHAR)+''''''+@NewLineChar;

but that put it in the format of...

AND
MEMBER_SPAN.YMDEFF<=''2015-04-01''
AND
MEMBER_SPAN.YMDEFF>=''2015-04-01''

Which is close...I think I just need to lose the "-"

View 5 Replies View Related

Transact SQL :: Due Date - Conversion Failed When Converting Date And / Or Time From Character String

Nov 16, 2015

SELECT * ,[Due]
  FROM [Events]
 Where Due >= getdate() +90

This returns the error: Conversion failed when converting date and/or time from character string

Why would this be? How to cast or convert this so that it will work? 

View 24 Replies View Related

Returning A Date In This Format DD/MM/YYYY

Mar 4, 2004

I basically want to return a date in DD/MM/YYYY format.

SELECT firstname, dbo.FormatDate(registrationdate) from T_Users

Is there an SQL Function that allows date formatting?

Thanks.

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved