現在,這是我在使用MSSQL時遇到的最奇怪的事情。查詢不帶參數,但不帶參數
我有一個表叫用戶,它有一排它有「管理員」在用戶名字段,當我運行下面的查詢,它並沒有給我任何結果:
DECLARE @uname varchar;
SET @uname = 'admin'
SELECT * FROM [User] WHERE UserName = @uname
但是當我運行它,我得到預期的結果:
SELECT * FROM [User] WHERE UserName = 'admin'
這是表的定義:
CREATE TABLE [dbo].[User](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[UserName] [nvarchar](256) NOT NULL,
[FirstName] [nvarchar](256) NULL,
[LastName] [nvarchar](256) NULL,
[Email] [nvarchar](512) NULL,
[Password] [binary](64) NULL,
[GroupID] [int] NOT NULL,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [UQ__Users__C9F284563A4F773F] UNIQUE NONCLUSTERED
(
[UserName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
我在C#應用程序中訪問這個數據庫,所以當我在SqlParameter中傳遞用戶名時,它只是給我沒有結果。
這裏是一個示例C#代碼:
string query = "SELECT COUNT(*) FROM [User] WHERE UserName = @uname";
using (var connection = new SqlConnection(ConnectionString))
{
connection.Open();
using (var cmd = new SqlCommand(query, connection))
{
cmd.Parameters.Add(new SqlParameter("uname", "admin"));
int rowCount = (int)cmd.ExecuteScalar();
}
}
我沒有得到任何的異常。
任何想法?
向我展示您遇到問題的代碼 – Chaitanya
@durga,我添加了C#代碼示例 – Glen
@在參數名稱中缺少。 –