SQL查询中的字符串和变量

时间:2016-04-12 01:11:13

标签: c# sql sql-server

我知道在C#中,我们可以在字符串中使用变量。

例如:

int num = 3;
string str = "hello, I have " + num + " apple"; 

我们如何在SQL查询中的insert语句中执行此操作?

假设我的表中有2列,它们是nameremarks,我想在我的存储过程中编写一个insert语句。

例如:

Declare @emp_no int;

Insert into employee (name, remarks) 
Values ('Joe', 'Employee's number' + @emp_no) 

我想知道我是否可以在查询中做这样的事情?

1 个答案:

答案 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=1DECLARE @emp_no INT; SET @emp_no=(SELECT EmpNo FROM Employee WHERE Something unique is true)
  • 之类的内容
  • “员工编号”中的单个qoute会破坏您要设置的字符串。在SQL字符串中,您必须加倍qoutes。
  • SQL Server中的
  • - 在C#中的其他内容 - 你无法在没有强制转换的情况下连接字符串和int
  • 如果“数字”这个词后面没有空格,那么员工的号码就会接近这个词......

您可以尝试这样的事情:

Declare @emp_no int=1;
    Insert into employee (name, remarks) 
    Values ('Joe', 'Employee''s number ' + CAST(@emp_no AS VARCHAR(10)))