我是编程新手,特别是在使用sql server时。我有一个带有文本框和提交按钮的用户页面。当用户在文本框中输入信息并按下按钮时,信息将添加到数据库中。在将所有信息添加到数据库之后,应该在数据库中创建一个UserID列.UserID应该包含UserLastName和AutoIncrementNumber(自动分配给新行的数据库列)我有一个此UserID的函数专栏,我不知道如何使一切工作。请帮我。 谢谢!
这是代码:
using (SqlConnection conn = new SqlConnection(@"Data Source=MyDataBase;Initial Catalog=MyDataBase;Integrated Security=True;"))
SqlCommand CmdSql = new SqlCommand
("INSERT INTO [tbluser] ([UserID],[UserLastName], [UserFirstName], [UserMiddleInitial] SELECT [dbo].[usernamehandle](@UserFirstName),@UserLastName, @UserFirstName, @UserMiddleInitial", conn);
conn.Open();
CmdSql.Parameters.AddWithValue("@UserLastName", txtNewUserLN.Text.ToString());
CmdSql.Parameters.AddWithValue("@UserFirstName", txtNewUserFN.Text.ToString());
CmdSql.Parameters.AddWithValue("@UserMiddleInitial", txtNewUserMI.Text.ToString());
CmdSql.Connection = conn;
CmdSql.ExecuteNonQuery();
conn.Close();
这是功能:
USE [MyDataBase]
GO
/****** Object: UserDefinedFunction [dbo].[usernamehandle] Script Date: 04/07/2013 17:25:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[usernamehandle]
(@newuserName nchar(10))returns nchar(10)
AS
BEGIN
DECLARE @s2 nchar(256)
SET @s2 = ''
DECLARE @p int
DECLARE @ULN char(256)
DECLARE @UNAI int
SELECT @ULN = UserLastName FROM tblUser
SELECT @UNAI = UserNameAutoIncre FROM tbluser
SET @s2 = @UNAI
while @p <=6 begin
DECLARE @c int
SET @c = ascii(substring(@newUserName, @p, 1))
SET @s2 += char(@c)
end
return @s2
end
答案 0 :(得分:1)
尝试在SQL中直接调用您的函数:
注意:请检查该功能的参数。我假设参数是用户的名字。
SqlCommand CmdSql = new SqlCommand
("INSERT INTO [tbluser] ([UserID],[UserLastName], [UserFirstName], [UserMiddleInitial]) SELECT [dbo].[usernamehandle](@UserFirstName), @UserLastName, @UserFirstName, @UserMiddleInitial, conn);
答案 1 :(得分:0)
您不能使用函数来插入数据,仅用于select语句的函数仅适用于DDL而不是DML,因为您必须使用存储过程。