Link to home
Start Free TrialLog in
Avatar of efarhat
efarhat

asked on

Stored procedure - Today's Date as temp variable.

i'm creating a stored proc.

CREATE PROCEDURE test

AS
      select convert(varchar(10), getdate(), 101) as TodaysDate

      INSERT INTO  TableName ( startDate, endDate )
      VALUES( TodaysDate, TodaysDate-5 )


how can i get this to work?
ASKER CERTIFIED SOLUTION
Avatar of ALaRiva
ALaRiva
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
CREATE PROCEDURE test
AS
DECLARE @TodaysDate DATETIME
SELECT   @TodaysDate = CONVERT(DATETIME,convert(varchar(10), getdate(), 101))

     INSERT INTO  TableName ( startDate, endDate )
     VALUES( @TodaysDate , @TodaysDate -5 )

This seems awkward since you're @TodaysDate-5 = 5 days ago, so the endDate would be earlier than the startDate.

Also, realize that when you convert to VARCHAR(5), then it's not a datetime...
Avatar of efarhat
efarhat

ASKER

ok, got it to work but i ran into a problem.  i had to delete a entry in the table and because the ID for one of the columns is an IDENTITY, I now have a missing ID. It doesn't recalculate?

| ID |  field2  |
   1      data1
   3      data3
An IDENTITY Field is not intended to be a sequential number.  It's simply put, an IDENTITY for that record.  It can't be duplicated and doesn't necessarily have to be sequential without gaps.  

HTH

-Anthony
First of all you don't need any variable to do this, just a simple insert...like in the example bellow:


CREATE PROCEDURE test

AS
     INSERT INTO  TableName ( startDate, endDate )
     VALUES( convert(varchar(10), getdate(), 101), convert(varchar(10), DateAdd(dd, -5, getdate()), 101))

Second as sugested above, you tried to use variables, and the syntax of variables is that they all start with an @... as it was sugested above.. :))


regards,
  xenon
If you want to "reset" your identity, you can use the DBCC CHECKIDENT function.  However, like was already said above, you're not guaranteed to have sequences without gaps in the future because of deletes and rolled back transactions...
identity is more for having a unique key, and a short one (is of int type)..... It does not guarantee that the values are like 1,2,3,4...... Why? because for example you delete a few records, and in the table you have 1 billion records... You think in this case it will update the other records just to have all consecutive values? Also as above sugested there are rollbacks...

So identity is an easy way to ensure that you have a field that have unique values, and that is short, and so the index on it will work very fast...

regards,
 xenon