将参数值传递给sql查询

时间:2016-03-20 20:39:57

标签: sql-server vb.net

简单的问题 - 有以下查询:

SELECT 
    CASE 
      WHEN r.number Is NULL THEN 1001
      WHEN r.number = 9999 THEN 10001
      ELSE r.number + 1 
    END number
FROM 
    (VALUES(123)) AS a(art)
LEFT JOIN
    (SELECT 
         PARSENAME(Nummer, 3) art,
         MAX(CAST(PARSENAME(Nummer, 2) AS INT)) number
     FROM 
         tbArtikel 
     WHERE 
         Nummer LIKE '123[.]%'
     GROUP BY 
         PARSENAME(Nummer, 3)) r ON r.art = a.art

我想在两个地方将值从参数传递给它 - 你看到123.我试过这样做但看起来有些不对劲,你能告诉我应该怎么做吗?

我就是这样做的(错误的):

Using cmd As New SqlCommand("SELECT CASE WHEN r.number Is NULL THEN 1001
                                                     WHEN r.number = 9999 THEN 10001
                                                     Else r.number + 1 End number
                                        FROM (VALUES(@producentNumber)) AS a(art)   -- this will search this number within inner query And make case..
                                        LEFT JOIN(
                                        -- Get producent (in Like) number And max number Of it (without Like it Get all producent numbers And their max number out Of all
                                        SELECT PARSENAME(Nummer, 3) art,
                                        MAX(CAST(PARSENAME(Nummer, 2) AS INT)) number
                                        FROM tbArtikel WHERE Nummer Like '@producentNumber[.]%'
                                        GROUP BY PARSENAME(Nummer, 3)
                                        ) r
                                        On r.art = a.art", con)

cmd.CommandType = CommandType.Text
cmd.Parameters.Add("@producentNumber", SqlDbType.Int)

1 个答案:

答案 0 :(得分:1)

你在这里遗漏了一些问题

Like ' + @producentNumber + '[.]%'

试试这个:

  Using cmd As New SqlCommand("SELECT CASE WHEN r.number Is NULL THEN 1001
                                                     WHEN r.number = 9999 THEN 10001
                                                     Else r.number + 1 End number
                                        FROM (VALUES(@producentNumber)) AS a(art)   -- this will search this number within inner query And make case..
                                        LEFT JOIN(
                                        -- Get producent (in Like) number And max number Of it (without Like it Get all producent numbers And their max number out Of all
                                        SELECT PARSENAME(Nummer, 3) art,
                                        MAX(CAST(PARSENAME(Nummer, 2) AS INT)) number
                                        FROM tbArtikel WHERE Nummer Like ' + @producentNumber + '[.]%'
                                        GROUP BY PARSENAME(Nummer, 3)
                                        ) r
                                        On r.art = a.art", con)
                cmd.CommandType = CommandType.Text
                cmd.Parameters.Add("@producentNumber", SqlDbType.Int)