简体   繁体   中英

Different results when executing the SQL Server query

In the program there is a part of the code, which executes the query:

string SPROC = "#Some MSSQL Query#";
comm.CommandType = CommandType.Text;
comm.CommandText = SPROC;
comm.Parameters.Add(new SqlParameter("@Parameter1", SqlDbType.VarChar, 50)).Value = PARAM1;
comm.Parameters.Add(new SqlParameter("@Parameter2", SqlDbType.VarChar, 20)).Value = PARAM2;
comm.CommandTimeout = CurrentSettings.SQLTimeout;

conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter(comm);
DataSet TempDS = new DataSet();
adapter.Fill(TempDS);

The dataset ( TempDS ) table is supposed to have around 20000 records (row count) but inside the program it is saying only 20 records while in debugging mode.

I ran the script separately on the same database table, which is being used in the SQL Server connection string, but in SQL Server Management Studio, it returned 20000 records as it is supposed to do.

The script looks some what like:

Select 
    [Table1].Column1,[Table2].Column1 
From 
    [Table1]
Inner Join 
    [Table2] on ([Table2].Column1 = [Table1].Column2)
Where 
    [Table2].Column1 = @Parameter1 
    and ([Table1].Column1 in (Select * from dbo.Split(@Parameter2,','))

It is the same script text, which the code executes as well.

Does anybody have any idea why the program code is only bringing back part of the record whereas the script in SQL Server Management Studio returns all the records?

PS I have also checked the SQLTimeOut and it is set to 240, so more than enough time to return the records properly. And @Parameter1 and @Parameter2 are string variables.

string PARAM1 = "Random1"; //in C#
string PARAM2 = "Random2,Random3,Random4,Random5"; //in C#
@Parameter1 = PARAM1
@Parameter2 = PARAM2

The value of string exceeds the parameter length in the C#

string PARAM2 = "Random2,Random3,Random4,Random5"; //in C#

comm.Parameters.Add(new SqlParameter("@Parameter2", SqlDbType.VarChar, 20)).Value = PARAM2;

so you need to allocate more length here

Try using AddWithValue : https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue(v=vs.110).aspx

NOTE: IF you do this, also be aware of the SPLIT function capacity of the input; it might need to be adjusted to some large value - search for some split functions that take large inputs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM