无法在数据库中存储带逗号的字符串

时间:2012-06-20 16:07:43

标签: c# sql-server tsql stored-procedures

我使用以下行在数据库中存储字符串,但目前无法将其存储为单个字符串。每次遇到字符串中的逗号时,它都会在数据库表中创建一个新行。

cmd.Parameters.AddWithValue("@ImageURL", String.Join(",", img.ToArray()));

有什么方法可以解决这个问题?

这是我定义表格的方式:

@ImageURL VARCHAR(max)

AS
BEGIN
  SET NOCOUNT ON added to prevent extra result sets from
  interfering with SELECT statements.
  SET NOCOUNT ON;


  Insert statements for procedure here
  insert into 
  DECLARE @String    VARCHAR(100) 

  SET @String =''            

  IF(LEN(@Images)>0)        
  BEGIN        
       DELETE FROM Business_images WHERE BusinessId=@BusinessId        
  END        

  WHILE LEN(@ImageURL) > 0              
  BEGIN           
    SET @String = LEFT(@ImageURL, ISNULL(NULLIF(CHARINDEX(',', @ImageURL) - 1, -1),  LEN(@ImageURL)))              
    SET @ImageURL = SUBSTRING(@ImageURL, ISNULL(NULLIF(CHARINDEX(',', @ImageURL), 0), LEN(@ImageURL)) + 1, LEN(@ImageURL)) 

    insert into Images(ImageURL) values (@String)
  END
END

1 个答案:

答案 0 :(得分:3)

string specialString = "this is silly, string,,not so special''special";
using (SqlConnection conn = new SqlConnection(connectionString))
{
    using (SqlCommand command = new SqlCommand("Insert into t1 (col1) VALUES (@parame)"))
    {
        command.Connection = conn;
        command.Parameters.AddWithValue("@parame",specialString);
        command.ExecuteNonQuery();
    }
}

仅供参考:我能够插入到sql server中。在我的情况下,col1的类型为nvarchar