要在SQL脚本命令中使用的VB.NET用户输入文本框

时间:2011-02-16 18:06:28

标签: sql sql-server vb.net

我正在尝试创建一个vb.net程序,该程序将要求用户在两个文本框中输入开始日期和结束日期。我想使用它们在我创建的存储过程中输入的这些日期来运行查询,该查询将根据这些日期返回结果。

这是我当前的SQL脚本。

SET NOCOUNT ON
DECLARE @DBNAME NVARCHAR(MAX)
DECLARE @DBNAME1 NVARCHAR(MAX)
DECLARE @varSQL NVARCHAR(MAX)
DECLARE **@BEGDATE DATE**
DECLARE **@ENDDATE DATE**

DROP TABLE "SQL-EDD5 TOTALS" 
CREATE TABLE "SQL-EDD5 TOTALS" 
(SERVERNAME NVARCHAR(128),
TOTAL_IMAGES INT, 
TOTAL_FILE_SIZE_MBS INT)

DECLARE DBNAME CURSOR FAST_FORWARD FOR
select name from sys.databases where [NAME] LIKE 'Z%' AND create_date between @BEGDATE  and @ENDDATE
ORDER BY [create_date]

OPEN DBNAME

FETCH NEXT FROM DBNAME INTO @DBname
WHILE (@@FETCH_STATUS=0)
BEGIN

    Set @varSQL='INSERT INTO "SQL-EDD5 TOTALS" (TOTAL_IMAGES, TOTAL_FILE_SIZE_MBS) 
    SELECT SUM(PGCOUNT), sum(filesize/1024/1024) FROM ['+@DBNAME+'].dbo.tbldoc 
    WHERE created between between @BEGDATE  and @ENDDATE'
    EXEC SP_EXECUTESQL @varSQL

    FETCH NEXT FROM DBNAME 
    INTO @DBNAME
    END

    CLOSE DBNAME
    DEALLOCATE DBNAME

    INSERT INTO "SQL-EDD5 TOTALS"(SERVERNAME)
    SELECT CONVERT (NVARCHAR (128), SERVERPROPERTY('MachineName')) AS 'SERVER NAME'

    SELECT SERVERNAME AS 'SERVER NAME',SUM(TOTAL_IMAGES) AS 'TOTAL IMAGES', SUM(TOTAL_FILE_SIZE_MBS) AS 'TOTAL FILE SIZE IN MBS'
    FROM "SQL-EDD5 TOTALS"
    GROUP BY [SERVERNAME] 
    ORDER BY [SERVERNAME] desc

这是我目前用于文本框的Vb.net脚本。我想将文本框中的数据链接到@BEGDATE DATE,@ ENDDATE DATE。这些是我想用来存储和使用用户输入的日期的变量。我该怎么做才能将它们联系起来。

这是脚本:

Protected Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    Dim BEGDATE As DateTime
    BEGDATE = "@BEGDATE"
End Sub

Protected Sub TextBox2_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
    Dim ENDDATE As DateTime
    ENDDATE = "@ENDDATE"
End Sub

结束班

1 个答案:

答案 0 :(得分:1)

首先,您不能以您认为可以的方式绑定(链接)SQL参数。

您需要做的是将文本设置为变量,然后在执行SQL语句之前将该变量设置为SQL参数。

您应该使用类似于以下内容的osme来执行脚本:

Using cn As SqlClient.SqlConnection(dbConnectionString)
   cn.Open()
   Using cmd AS SqlCleint.SqlCommand(cn)
       cmd.CommandText = "Select * From Table Where Between(@BeginDate, @EndDate)
       cmd.Parameters.AddWithValue("@BeginDate", BeingDate)
       cmd.Parameters.AddWithValue("@EndDate", EndDate)

       cmd.ExecuteNonQuery()
       'Or cmd.ExecuteQuery()
   End Using
End Using

这将用相关的参数值替换@BeginDate和@EndDate的所有实例