sqlserver利用存儲過程去除重復行的sql語句

以前弄過類似,去除相同信息的方法,現在找不到了,不過今天又花一些時間給弄出來了,記錄一下

還是先上代碼吧 ,可以先看
代碼如下:
ALTER procedure [dbo].[PROC_ITEMMASTER_GETUNIQUE] @PAGEINDEX INT,@uid int,@itemnumber varchar(50)
AS
begin tran –開始事務
drop table [ItemMaster].[dbo].[testim] –刪除表
–把不重復記錄轉存到testim中
select * into [ItemMaster].[dbo].[testim] from [ItemMaster].[dbo].[dat_item_master] where item_uid in(select min(item_uid) as item_uid from [ItemMaster].[dbo].[dat_item_master] group by item_number) and status=0
select top 10 * from [ItemMaster].[dbo].[testim] where item_uid not in (select top (10*(@PAGEINDEX-1)) item_uid from [ItemMaster].[dbo].[testim])
and owneruid=@uid and item_number like @itemnumber+’%’

–判斷是否出錯
if @@error0
begin
rollback tran –出錯則回滾
end
else
begin –否則提前事務
commit tran
end

我的數據是這樣的:因為item_uid是標識列,item_number有重復的,

我想過濾成這樣:

順帶說幾個在編程的時候遇到的小問題

1.程序 出現 Could not find stored procedure 找不到這個存儲過程

因為我的程序數據庫有四個,而默認連接是A,但實際要執行B庫里的存儲過程,導致出錯,

解決辦法1:可在A里面建個一樣的存儲過程2:在執行連接的時候,替換下數據庫就行了

2. asp.net/C# 將存儲過程中返回的數據集,填充到dataset/datatable

代碼如下:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[“SolutionSQLServer”].ToString());
SqlCommand cmd = new SqlCommand(“Test”,conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(“@MaxId”, SqlDbType.Int).Value = 12000;

SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);

在這感謝 http://www.cnblogs.com/liujuncm5/archive/2009/08/31/1557569.html

3.在存儲過程里面,寫SQL語句不能動態不加order by 功能

比如

代碼如下:
–·@new_orderby 是傳入參數,不能這樣寫
select top (10*(2-1)) item_uid from testim order by @new_orderby

–執行這個的時候,SQL會出現 The SELECT item identified by the ORDER BY number 1 contains a variable as part
of the expression identifying a column position. Variables are only allowed when
ordering by an expression referencing a column name.

不過我找到解決辦法,不過很麻煩,

(第二個回答用 ‘ sql ‘進行連接)

(用case end 也行)

4. select into 和 insert into select 兩種復制文句 (這里感謝)

  1.

語句形式為:

  2.

語句形式為:

5.順便復習下常用的SQL方法語句
代碼如下:
declare @name varchar(200) –聲明變量
set @name=’abcd;def’ –賦值
print ‘exec len :’+Convert(varchar(10),Len(@name)) –convert(type,value)轉換,Len(value)獲取大小
print ‘exec charindex:’+Convert(varchar(10),CharIndex(‘e’,@name))–CharIndex(find,value) 在value中查找find的位置
print ‘not replace:’+@name
print ‘exec replace:’+Replace(@name,’;’,”) –用replace替換
print ‘exec substring:’+Substring(@name,0,3)–用substring截取
print @@RowCount –返回上一行代碼受影響的行數

作者:

? 版權聲明
THE END
喜歡就支持一下吧
點贊9 分享