如何在sql server中插入特定列

时间:2014-11-04 11:36:02

标签: asp.net sql-server

我有Student Attendence表,并且列有

这样的列
st_id  |  StudentName  |   month  |  year  |  day1 to day30

而且,我正在使用asp.net。当我单击“显示”按钮时,数据库的列应插入st_idStudentNamemonthyear的值,日期应为systemdate。 date应该在sql的day列中输入,剩下的应该是null值

suppose if i enter the date today ie, 4 data will enter in day4 col like present

http://i.stack.imgur.com/K7LwU.png

1 个答案:

答案 0 :(得分:2)

试试这个

DECLARE @st_id int=1
DECLARE @StudentName varchar(50)='dinesh'
DECLARE @month varchar(50)='jan'
DECLARE @year int=2014

DECLARE @SQL nvarchar(MAX)= 'insert into 
(st_id, StudentName, month, year,day'+CAST(datepart(day,GETDATE()) as 
varchar(10))+') values  
('+CAST(@st_id as VARCHAR(MAX))+','''+@StudentName+''','''+
CAST(@month as VARCHAR(MAX))
+''','+CAST(@year as VARCHAR(10))+',''present'')'
print @SQL 

使用程序

Create procedure sp_insertStudents
@st_id int,
@StudentName varchar(50),
@month varchar(50),
@year int
as
BEGIN


DECLARE @SQL nvarchar(MAX)= 'insert into 
(st_id, StudentName, month, year,day'+CAST(datepart(day,GETDATE()) as 
varchar(10))+') values  
('+CAST(@st_id as VARCHAR(MAX))+','''+@StudentName+''','''+
CAST(@month as VARCHAR(MAX))
+''','+CAST(@year as VARCHAR(10))+',''present'')'
print @SQL 
EXEC(@SQL)
END

<强>输出

insert into (st_id, StudentName, month, year,day4) values  
(1,'dinesh','jan',2014,'present')