我知道在C#中,我们可以在字符串中使用变量。
例如:
int num = 3;
string str = "hello, I have " + num + " apple";
我们如何在SQL查询中的insert语句中执行此操作?
假设我的表中有2列,它们是name
和remarks
,我想在我的存储过程中编写一个insert语句。
例如:
Declare @emp_no int;
Insert into employee (name, remarks)
Values ('Joe', 'Employee's number' + @emp_no)
我想知道我是否可以在查询中做这样的事情?
答案 0 :(得分:3)
在这部分中有几个缺陷:
Declare @emp_no int;
Insert into employee (name, remarks) Values ('Joe', 'Employee's number' + @emp_no)
一个接一个......
@emp_no
声明为int
,但没有分配值...如果您连接SQL字符串并且其中一个为NULL,则整个字符串将为NULL ...所以更好使用DECLARE @emp_no INT=1
或DECLARE @emp_no INT; SET @emp_no=(SELECT EmpNo FROM Employee WHERE Something unique is true)
您可以尝试这样的事情:
Declare @emp_no int=1;
Insert into employee (name, remarks)
Values ('Joe', 'Employee''s number ' + CAST(@emp_no AS VARCHAR(10)))