So i need to figure out how i can get a record count value and use that count as a new value to insert into a table.
开发者_C百科Ex: In My Stored Procedure
@Count int
What im looking for
@Count to equal "select top (1) _fieldName from _someTable order by _fieldName Desc"
Finally
insert into _newTable (_fieldName) values (@Count)
End
I dont have to use a variable, just trying to demonstrate what im really trying to do. My SQL knowledge is pretty limited so no laughing, or smirking! ;)
In SQL SERVER
DECLARE @Count INT
SET @COUNT = SELECT COUNT(*) FROM SomeTable
insert into newTable (fieldName) values (@Count)
OR
INSERT INTO newTable (fieldName)
SELECT COUNT(*) FROM SomeTable
You should use an INSERT-SELECT
. That is an INSERT
that uses all the rows returned from the SELECT
as the values to insert. So try something like this (SQL Server example code):
DECLARE @TableToCount table (fieldName varchar(5))
INSERT INTO @TableToCount VALUES ('A')
INSERT INTO @TableToCount VALUES ('B')
INSERT INTO @TableToCount VALUES ('C')
DECLARE @TableToStore table (fieldName int)
INSERT INTO @TableToStore
(fieldName)
SELECT
COUNT(fieldName)
FROM @TableToCount
SELECT * FROM @TableToStore
OUTPUT:
fieldName
-----------
3
(1 row(s) affected)
If you are using SQL Server, then why not use the @@ROWCOUNT
Not sure which database, so I'll write Sybasish.
declare @count int
select @int = count (1) from ... the rest of your query
insert another_table values (@count, 'other_field')
What i was looking for was the identity of the insert during the stored proc. complete this a while back but wanted to post the final answer.
SELECT SCOPE_IDENTITY()
精彩评论