想把sql语句:select top 2 id from ArticleInfo 写成select top @CustomCount id from ArticleInfo 
然后用SqlParameter 来做:
    private SqlParameter[] GetArticleTypeIdAndCustomCountParam(int CustomCount)
    {
        SqlParameter[] param = new SqlParameter[]
        {
            new SqlParameter("@CustomCount ",SqlDbType.Int)
        };
        param[0].Value = CustomCount;
        return param;
    }
    public DataTable GET_ArticleInfoLIST_CustomByType(int CustomCount)
    {
        DataTable dt = null;
        SqlParameter[] param = this.GetArticleTypeIdAndCustomCountParam(CustomCount);
        try
        {
            dt = RunSQLGatDataTable("select top @CustomCount id from ArticleInfo ", param);
        }
        catch { }
        return dt;
    }
    public static DataTable RunSQLGatDataTable(string sqlString, SqlParameter[] sqlparam)
    {
        DataTable dt = new DataTable();
        string sqlConStr = System.Configuration.ConfigurationManager.AppSettings.Get("sqlConStr");
        SqlConnection sqlConn = new SqlConnection(sqlConStr);
        SqlCommand sqlComm = new SqlCommand(sqlString, sqlConn);
        for (int j = 0; j < sqlparam.Length; j++)
        {
            sqlComm.Parameters.Add(sqlparam[j]);
        }
        SqlDataAdapter ada = new SqlDataAdapter(sqlComm);
        try
        {
            ada.Fill(dt);
        }
        catch (Exception exp)
        {
        }
        return dt;
    }可是它运行起来总是报@CustomCount 地方错误:{"Line 1: Incorrect syntax near '@CustomCount'."}

解决方案 »

  1.   

    http://msdn.microsoft.com/zh-cn/library/ms176104.aspxTOP expression [ PERCENT ] [ WITH TIES ] 
    指示只能从查询结果集返回指定的第一组行或指定的百分比数目的行。expression 可以是指定数目或百分比数目的行。 
    这样看来expression 只能是常数
      

  2.   

    exec (‘select top’+@CustomCount +‘id from ArticleInfo  ’)
      

  3.   

    set rowcount +@CustomCount 
    select id from ArticleInfo  
    你再设置升序与降序!!!!
      

  4.   

    to:yagebu1983 
    没太明白exec (‘select top’+@CustomCount +‘id from ArticleInfo  ’)是什么意思,能说清楚一些吗
      

  5.   

    把query写成一个存储过程里面就可以使用参数了
      

  6.   

    在select到from之间不可以使用参数
    参数只能用在条件里面,给你一个思路吧
    现取出来,然后显示的时候在过滤成你想要的条数,在表现层做
      

  7.   

    把查询写成一个存储过程CREATE PROCEDURE [dbo].[sp_name]
    (   

    @CustomCount  DECIMAL

    )
    AS
    BEGIN
    DECLARE @str VARCHAR(8000)
    SET @str='select * from table '
    IF @CustomCount<>0
    SET @str=@str+' where CustomCount='+@CustomCount
    EXEC(@str)
    END
      

  8.   

    这样试一下
    "select top ‘“+CustomCount.ToString()+”’ id from ArticleInfo“ 
      

  9.   


        public DataTable GET_ArticleInfoLIST_CustomByType(int CustomCount)
        {
            DataTable dt = null;
            SqlParameter[] param = this.GetArticleTypeIdAndCustomCountParam(CustomCount);
            try
            {
                dt = RunSQLGatDataTable("select top "+CustomCount+" id from ArticleInfo ", param);
            }
            catch { }
            return dt;
        }