2011-03-16 81 views
0

有沒有遇到過這種年齡,當我搜索我找不到解決方案。我認爲它被稱爲SQL重載。基本上,當我有「」(一個空字符串)的SQL中的任何參數,我不想在數據庫中設置一個值...我該如何解決這個常見的SQL問題

注意:我想要在SQL級別做它不做在C#級別,因爲它的馬虎這樣。

string Sql = "IF NOT EXISTS (SELECT * FROM tbl_FileSystemReferences) " 
      + "INSERT INTO tbl_FileSystemReferences (UploadDir) VALUES (null) " 
      + "UPDATE tbl_FileSystemReferences SET " 
      + "[email protected], " 
      + "[email protected], " 
      + "[email protected], " 
      + "[email protected], " 
      + "[email protected], " 
      + "[email protected], " 
      + "[email protected], " 
      + "[email protected], " 
      + "[email protected], " 
      + "[email protected] "; 

SqlCommand Command = new SqlCommand(Sql); 
Command.Parameters.AddWithValue("@UploadDir", f.UploadDir); 
Command.Parameters.AddWithValue("@ThumbnailDir", f.ThumbnailDir); 
Command.Parameters.AddWithValue("@ArchiveDir", f.ArchiveDir); 
Command.Parameters.AddWithValue("@RealDir", f.RealDir); 
Command.Parameters.AddWithValue("@FlashDir", f.FlashDir); 
Command.Parameters.AddWithValue("@AssociatedFilesDir", f.AssociatedFilesDir); 
Command.Parameters.AddWithValue("@EnableArchiving", f.EnableArchiving); 
Command.Parameters.AddWithValue("@AppWideDir", f.AppWideDir); 
Command.Parameters.AddWithValue("@FFmpegDir", f.FFmpegDir); 
Command.Parameters.AddWithValue("@InstallationDir", f.InstallationDir); 

ExecuteNonQuery(Command); 

我知道有一種方法我用存儲過程來做到這一點我只是不能記得(我認爲這就是所謂的超載)....

乾杯,

回答

0

一個辦法是在存儲過程,在那裏你會得到所有的參數,然後將查詢之前或者:

  • 您允許通過空
  • 你轉換每個參數爲空,如果它們是空的:

    選擇@UploadDir =空在那裏@UploadDir =「」

你會怎麼做,對所有的參數,然後在更新查詢:

IF NOT EXISTS (SELECT * FROM tbl_FileSystemReferences) 
INSERT INTO tbl_FileSystemReferences (UploadDir) VALUES (null) 
UPDATE tbl_FileSystemReferences SET 
UploadDir=coalesce(@UploadDir, UploadDir), 
ThumbnailDir=coalesce(@ThumbnailDir, ThumbnailDir), 
ArchiveDir=coalesce(@ArchiveDir, ArchiveDir), 
RealDir=coalesce(@RealDir, RealDir), 
FlashDir=coalesce(@FlashDir, FlashDir), 
AssociatedFilesDir=coalesce(@AssociatedFilesDir, AssociatedFilesDir), 
EnableArchiving=coalesce(@EnableArchiving, EnableArchiving), 
AppWideDir=coalesce(@AppWideDir, AppWideDir), 
FFmpegDir=coalesce(@FFmpegDir, FFmpegDir), 
InstallationDir=coalesce(@InstallationDir, InstallationDir) 
2

可以在創建一個存儲過程而不是將命令作爲文本傳遞?

這樣,你可以打破各像線「UploadDir = @ UploadDir,」到了自己的變量,只能將其添加到命令,如果它不是空或不是空字符串

+0

不是我們真正使用內聯SQL與參數SQL是對我們來說太過於矯枉過正。我明白你的意思,儘管它很有用。 – Exitos 2011-04-05 08:32:49