473,729 Members | 2,328 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Getting the last inserted row by smalldatetime

17 New Member
I am creating a Stored Proc and I need to be able to select the last added row, now this should be made easier by the fact that I have a smalldatetime column in the table that is added every time a new row is inserted. I use MSSQL 2005 and the construction of the table is this:
Expand|Select|Wrap|Line Numbers
  1. CREATE TABLE temp_sensor_table
  2.     (    
  3.     temp_id Int Identity PRIMARY KEY,
  4.     device_id Int NOT NULL
  5.         REFERENCES Devices(device_id),
  6.     temp_value NVARChar(10) NOT NULL,
  7.     temp_date smalldatetime NOT NULL DEFAULT GETDATE()
  8.     )
  9.  
And the select statement that i have is this:
Expand|Select|Wrap|Line Numbers
  1. select temp_value 
  2. from temp_sensor_table 
  3. where device_id = @device_id_temp 
  4. and temp_date = ???
  5.  
The @device_id_temp is just an int that is selected in another select statement in the Stored Proc, what I need is the last part of the where statement.

NormannTheDane
Sep 13 '07 #1
4 3853
almaz
168 Recognized Expert New Member
Expand|Select|Wrap|Line Numbers
  1. ;with Ordered(temp_value, Position) as
  2. (
  3.     select temp_value, Position = row_number() over(order by temp_date desc)
  4.     from temp_sensor_table 
  5.     where device_id = @device_id_temp 
  6. )
  7. select temp_value 
  8. from Ordered 
  9. where Position = 1
Sep 13 '07 #2
Normann
17 New Member
The select statement from above works perfectly, if it is on it's own but when I try to use it in the Stored Proc I get an error.

I think it is when I try to use it to set a parameter, but I might be wrong. I have include what I am trying to do, and I hope someone can spot what I am doing wrong.

Expand|Select|Wrap|Line Numbers
  1. CREATE PROCEDURE dbo.SP_Get_Data_Status
  2. (
  3. @room_name nvarchar(20),            --Input vari from C#
  4. @temp_value nvarchar(4) output,            --Output vari to C#    
  5. @humid_value nvarchar(4) output            --Output vari to C#
  6. )
  7. AS
  8.     DECLARE @room_id int            
  9.     DECLARE @device_type_id_temp int        
  10.     DECLARE @device_type_id_humid int    --Vari used in 
  11.     DECLARE @device_type_id_fire int       --the Stored Proc
  12.     DECLARE @device_id_temp int        
  13.     DECLARE @device_id_humid int        
  14.  
  15.  
  16. SET @room_id = (                    --Gets the room ID 
  17. select room_id from Rooms            --from Rooms Table
  18. where room_name = @room_name)        --using @room_name
  19.  
  20. SET @device_type_id_temp = (            --Gets the type ID 
  21. select device_type_id from Device_Type          --from Device_Type Table
  22. where device_type_name = 'temp')        --using @room_id
  23.  
  24. SET @device_type_id_humid = (            --Gets the type ID
  25. select device_type_id from Device_Type           --from Device_Type Table
  26. where device_type_name = 'humid')        --using @room_id
  27.  
  28. SET @device_id_temp = (                       --Gets the device ID
  29. select device_id from Devices                --from Devices Table
  30. where room_id = @room_id and            --using @room_id &
  31. device_type_id = @device_type_id_temp)        --@device_type_id_temp
  32.  
  33. SET @device_id_humid = (              --Gets the device ID
  34. select device_id from Devices                --from Devices Table
  35. where room_id = @room_id and            --using @room_id &
  36. device_type_id = @device_type_id_humid)        --@device_type_id_humid
  37.  
  38.  
  39. --Code from TheScripts.com forum By almaz Thread_id: 707431
  40. ;with Ordered(temp_value, Position) as        
  41. (
  42. select temp_value, Position = row_number() 
  43. over(order by temp_date desc)
  44. from temp_sensor_table
  45. where device_id = '1'
  46. )
  47. SET @temp_value = (    --<-- Error happens here
  48. select temp_value
  49. from Ordered
  50. where Position = 1)
  51.  

When I try to execute it the error I recive is:

Msg 156, Level 15, State 1, Procedure SP_Get_Data_Sta tus, Line 45
Incorrect syntax near the keyword 'SET'.
Sep 13 '07 #3
almaz
168 Recognized Expert New Member
;with Ordered(temp_va lue, Position) as
(
select temp_value, Position = row_number()
over(order by temp_date desc)
from temp_sensor_tab le
where device_id = '1'
)
select @temp_value = temp_value
from Ordered
where Position = 1
Sep 14 '07 #4
Normann
17 New Member
Thank you very much for your help, it is working now

NormannTheDane
Sep 14 '07 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

16
2294
by: Robbie | last post by:
Hi All This is a belter that my little brain can't handle. Basically I have 1 SQL table that contains the following fields: Stock Code Stock Desc Reference Transaction Date
2
16070
by: ImraneA | last post by:
Hi there Application : Access v2K/SQL 2K Jest : Using sproc to append records into SQL table Jest sproc : 1.Can have more than 1 record - so using ';' to separate each line from each other.
3
28765
by: siatki | last post by:
Hello, Firstly, sorry for my english. I have problem with creating SQL statement. I am beginner and I think that it is very easy to do. Look - I have to get only the last 20 records from table ABC (f.eg.) and according to that how to create the SQL statement? F.eg. SELECT name, forename, date FROM abc WHERE.... You know - how to finish the statement to get only 20 records lastly inserted into the table? Thanks and I am waiting for...
5
5758
by: Ray via SQLMonster.com | last post by:
Hi there, See if you can help me with the following: I need to write an SQL code that will return me: The 1st day & the Last day of the Previous Month in the following format (smalldatetime): yyyy-mm-dd hh:mi:ss (24h)
2
7567
by: mgarriss | last post by:
Given this table: CREATE TABLE test ( id SERIAL, example TEXT ); An implicit sequence is created as show in this message: NOTICE: CREATE TABLE will create implicit sequence 'test_id_seq' for SERIAL column 'test.id' How do I retrieve the last 'id' that was inserted? I have a process
3
2587
by: Mark | last post by:
I'm using ASP.Net to accress a database, what I need to do is get the fields out of the very last record in the db. How do I do this? Actually I'm after the primary key, titled 'AdID' it'll tell me what number this last record is. so I can tell what number the next record inserted will be. How do I do this? Thanks,
13
10141
by: dbuchanan | last post by:
Hello, Here is the error message; ---------------------------- Exception Message: ForeignKeyConstraint Lkp_tbl040Cmpt_lkp302SensorType requires the child key values (5) to exist in the parent table. ----------------------------
6
7655
by: SQL Server | last post by:
I've been working this for a while. Kind of new to SQL Server functions and not seeing what I am doing wrong. I have this function CREATE FUNCTION dbo.test (@Group varchar(50)) RETURNS smalldatetime AS BEGIN Declare @retVal varchar(10) (SELECT @retVal= MIN() FROM dbo.t_master_schedules WHERE (event_id = 13) AND (group_ =@Group)) return convert(smalldatetime, @retVal, 1)
1
3029
davydany
by: davydany | last post by:
Hey guys...a n00b Here for this site. I'm making a sequence class for my C++ class. And The thing is in the array that I have, lets say i put in {13,17,38,18}, when i see the current values for the array data from 0 to3, I get this {13, JUNK VALUE, 17,38, 18} and JUNK VALUE is like 1.8e831 or something like that. This happens when I use the attach() function and use the current() function to display the values at data I really want to...
0
8921
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9427
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9284
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9202
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9148
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4528
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4796
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2165
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.