Click here to Skip to main content
15,919,774 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have table emp and one column is there name empmachineid.
i want to insert number from 1 to end ...

like
1
2
3
4
5
all others columns are filled..
Posted
Comments
PIEBALDconsult 19-Aug-13 0:47am    
Why?

Have a look at example:
SQL
DECLARE @tmp TABLE (empName VARCHAR(30), EmpId INT NULL)

INSERT INTO @tmp (empName)
SELECT 'A'
UNION ALL SELECT 'B'
UNION ALL SELECT 'C'
UNION ALL SELECT 'D'
UNION ALL SELECT 'E'
UNION ALL SELECT 'F'
UNION ALL SELECT 'G'

UPDATE t1 SET t1.EmpId = t2.EmpId
FROM @tmp AS t1 INNER JOIN (
	SELECT ROW_NUMBER() OVER(ORDER BY empName) AS EmpID, empName
	FROM @tmp
	) AS t2 ON t1.empName = t2.empName

SELECT EmpID, empName
FROM @tmp

Result:
1	A
2	B
3	C
4	D
5	E
6	F
7	G
 
Share this answer
 
v2
Comments
_Asif_ 19-Aug-13 7:30am    
This is not a good approach. Arun approach is better
Maciej Los 19-Aug-13 7:33am    
Could you exaplain me, why?
_Asif_ 19-Aug-13 9:13am    
This approach is more resource intensive, first a temporary table, then a select with unions, then one more select finally leading to an update! No need to use a tank if a problem can be killed by a hammer.
Maciej Los 19-Aug-13 9:29am    
:laugh:
Man, it is an example! I had created temporary table with names of employees to show how to add column with numbers 1, 2, 3 "to the end", then i used ROW_NUMBER() function to create id's.

Oh Gosh...
_Asif_ 20-Aug-13 0:20am    
Well, in that case it should have been written as "comments" :)
Try this code.

SQL
declare @a int
set @a =  0


update emp
set  @a =  @a+1,
empmachineid  = Convert(varchar(2),@a)
 
Share this answer
 
v2
Comments
Nawab Ahmad 19-Aug-13 0:40am    
Hi,

Msg 425, Level 16, State 1, Line 4
Data type int of receiving variable is not equal to the data type nvarchar of column 'empmachineid'.
ArunRajendra 19-Aug-13 0:52am    
Try the modified code. Modify Varchar(2) to as per your field length.
Does this help?
CREATE TABLE [cpqa].[tbl_NA_strFaint](
   [strFaint_00][nvarchar](MAX)
    )

INSERT INTO [cpqa].[tbl_NA_strFaint]
	VALUES ('UNION ALL SELECT A'),
				('UNION ALL SELECT B'),
					('UNION ALL SELECT C'),
						('UNION ALL SELECT D')

CREATE TABLE [cpqa].[tbl_NA_strFaintIdx](
    [Idx][int]IDENTITY(1,1),
        [strFaint_00][nvarchar](MAX)
        )

INSERT INTO [cpqa].[tbl_NA_strFaintIdx]
	SELECT [strFaint_00] FROM [cpqa].[tbl_NA_strFaint]	

SELECT [Idx], [strFaint_00] FROM [cpqa].[tbl_NA_strFaintIdx]

Idx	strFaint_00
~~~~~~~~~~~~~~~~~~~~~~~~~~
1	UNION ALL SELECT A
2	UNION ALL SELECT B
3	UNION ALL SELECT C
4	UNION ALL SELECT D
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900