0

text我对 SQL Server 2008 中的数据类型非常陌生

我创建了表:

CREATE TABLE sample(id int identity,name varchar(20),Yell_Your_self text) 

但我在插入时遇到问题

insert into sample values('ganesh','welcome to india')
insert into sample values('ganesh','welcome to india's largest temple')

第一条语句工作正常,但如何执行第二条语句?

4

5 回答 5

3

试试这个——

IF OBJECT_ID(N'dbo.sample') IS NOT NULL
   DROP TABLE dbo.[sample]

CREATE TABLE dbo.[sample]
(
      id INT IDENTITY(1,1) PRIMARY KEY
    , name VARCHAR(20)
    , Yell_Your_self VARCHAR(2000)
)

INSERT INTO dbo.[sample] 
VALUES
    ('ganesh', 'welcome to india'), 
    ('ganesh', 'welcome to india''s largest temple')

更新3:

public int get(string val1,string val2) 
{ 
    using(SqlConnection con = new SqlConnection(connectionString))
    {
        con.Open();

        int i = 0;

        using (SqlCommand cmd = new SqlCommand("INSERT INTO dbo.sample (name, Yell_Your_self) VALUES(@val1, @val2)", con))
        {
            cmd.Parameters.AddWithValue("@val1", val1);
            cmd.Parameters.AddWithValue("@val2", val2);
            i = cmd.ExecuteNonQuery();
        }

        con.Close();
        return i;
    }
}
于 2013-05-07T13:36:01.497 回答
1

可能在印度的撇号上抛出错误

insert into sample values('ganesh','welcome to india''s largest temple')
于 2013-05-07T13:36:29.513 回答
1

问题是字符串中有一个单引号,而单引号是 SQL 中的字符串分隔符。

尝试:

INSERT INTO  sample VALUES ('ganesh','welcome to india''s largest temple')
于 2013-05-07T13:37:13.863 回答
0

正如您已经知道 SQL 面临的问题是在查询中转义撇号,我猜这是固定的。要回答关于如何从 C# 等前端传递值的第二个问题,参数化查询是一种好方法。作为替代方案,您可以使用这个也涉及字符串操作来准备查询:

public int get(string val1,string val2) 
{ 
    string temp = string.Concat(val1,"," + val2); // concatenate all your params
    temp = temp.replace("'","''").replace(",","','");  // replace any single qoute with escaped single quote
    string s="insert into sample values('" + temp +  "')"; // append altered string in query
    SqlCommand cmd = new SqlCommand(s,con); 
    con.Open(); 
    int i = cmd.ExecuteNonQuery(); 
    con.Close(); 
    return i; 
}

希望能帮助到你!

于 2013-05-08T05:56:19.700 回答
0

尝试传递动态值

insert into sample values(@name, N''' + @Yell_Your_self text + ''' )
于 2014-01-10T12:07:14.747 回答