您的位置:首页 > 数据库

常用 SQL 语句总结 (主要是存储过程中的使用)

2007-04-27 16:12 756 查看
一.存储过程中判别记录是否存在
1.
if(exists(select * from UserInfo where UserId=@userId and UserPwd=@oldPwd))
begin
update UserInfo set UserPwd=@newPwd where UserId=@userId
set @result=1
end
else
begin
set @result=-1
end
2.
declare @password nvarchar(50)
select @password = userpwd from userinfo where userID = @userId
if @password = @oldpassword
begin
update userinfo set userPwd = @newPassword where userId = @userId
set @result = 1
end
else
begin
set @result = -1
end
3.
select userId from UserInfo where UserName=@userName
通过类型转换后判断userId的值,若等于0就表示不存在。
二。程序中写SQL语句时,变量的使用。
如cmd.ComandText="select * from NewsDetail where NewsTypeId="+this.newsTypeId;
或着cmd.ComandText="select * from NewsDetail where NewsTypeId='"+this.newsTypeId+"'";(两单引号内加两双引号)
三.存储过程中如何获取自动增加的值
select @orderId=@@identity
四.isnull的使用。
ISNULL
使用指定的替换值替换 NULL。
语法
ISNULL ( check_expression , replacement_value )

参数
check_expression

将被检查是否为 NULL的表达式。check_expression 可以是任何类型的。

replacement_value

在 check_expression 为 NULL时将返回的表达式。replacement_value 必须与 check_expresssion 具有相同的类型。

返回类型
返回与 check_expression 相同的类型。

注释
如果 check_expression 不为 NULL,那么返回该表达式的值;否则返回 replacement_value。

示例
A. 将 ISNULL 与 AVG 一起使用
下面的示例查找所有书的平均价格,用值 $10.00 替换 titles 表的 price 列中的所有 NULL 条目。

USE pubs
GO
SELECT AVG(ISNULL(price, $10.00))
FROM titles
GO
下面是结果集:
--------------------------
14.24

(1 row(s) affected)

B. 使用 ISNULL
下面的示例为 titles 表中的所有书选择书名、类型及价格。如果一个书名的价格是 NULL,那么在结果集中显示的价格为 0.00。
USE pubs
GO
SELECT SUBSTRING(title, 1, 15) AS Title, type AS Type,
ISNULL(price, 0.00) AS Price
FROM titles
GO
下面是结果集:

Title Type Price
--------------- ------------ --------------------------
The Busy Execut business 19.99
Cooking with Co business 11.95

The Psychology UNDECIDED

c.在存储过程中获取新闻与新闻的前一条和后一条的标题
create procedure GetNews
(
@newsId int
)
as
declare
@priorId int,
@nextId int,
@priorTitle nvarchar(50),
@nextTitle nvarchar(50)
select @priorId=isnull(max(newsId),0) from NewsDetail where NewsId< @newsId
select @priorTitle=NewsTitle from NewsDetail where NewsId= @priorId
select @nextId=isnull(min(newsId),0) from NewsDetail where NewsId> @newsId
select @nextTitle=NewsTitle from NewsDetail where NewsId= @nextId
select
NewsTitle,NewsTime,NewsContent,Hit,@priorTitle as priorTitle,@nextTitle as nextTitle
from
NewsDetail
where
NewsId=@newsId

五.inner join 的使用
INNER JOIN 运算
组合两个表中的记录,只要在公共字段之中有相符的值。
语法
FROM table1 INNER JOIN table2 ON table1.field1 compopr table2.field2
table1, table2 记录被组合的表的名称。
field1, field2 被联接的字段的名称。若它们不是由数字构成的,则这些字段必须为相同的数据类型并包含同类数据,但它们无须具有相同的名称。
compopr 任何的关系比较运算子:"=," "<," ">," "<=," ">=," 或 "<>."

说明
可以在 FROM 子句中使用INNER JOIN运算。.这是最普通的联接类型。只要在这两个表的公共字段之中有相符值,内部联接将组合两个表中的记录。

可以使用 INNER JOIN 与部门表及员工表选择每一个部门中的全部员工。反之,可以使用 LEFT JOIN或 RIGHT JOIN运算创建 outer join,从而选择所有部门(即使有些并没有员工)或所有员工(即使有些尚未分配到部门)。

若试图联接包含 Memo或 OLE Object数据的字段,会导致错误。

可以联接任何两个相同类型的数值字段。例如,可以联接 AutoNumber和 Long字段,因为它们类型相似。但不能联接 Single 和 Double 类型的字段。

下列示例显示如何在类标识符字段联接类表及产品表:

SELECT CategoryName, ProductName

FROM Categories INNER JOIN Products

ON Categories.CategoryID = Products.CategoryID;

在上面的示例中,类标识符是已被联接的字段,但是它并不包含在查询输出中,因它并非被包含在 SELECT 语句之中。在这个示例中,若要包含联接字段,将字段名包含在 SELECT 语句中, Categories.CategoryID.

也可以使用下列语法,在一个 JOIN 语句中链接多个 ON 子句:

SELECT fields
FROM table1 INNER JOIN table2
ON table1.field1 compopr table2.field1 AND
ON table1.field2 compopr table2.field2) OR
ON table1.field3 compopr table2.field3)];

也可以使用下列语法,嵌套 JOIN 语句:

SELECT fields
FROM table1 INNER JOIN
(table2 INNER JOIN [( ]table3
[INNER JOIN [( ]tablex [INNER JOIN ...)]
ON table3.field3 compopr tablex.fieldx)]
ON table2.field2 compopr table3.field3)
ON table1.field1 compopr table2.field2;

在一个 INNER JOIN 之中,可以嵌套 LEFT JOIN 或 RIGHT JOIN,但是在 LEFT JOIN 或 RIGHT JOIN 中不能嵌套 INNER JOIN。

六.在存储过程中的模糊查询

string sql="select * from Article where pass=1 and deleted=0 and Title like '%"+@keyword+"%' order by UpdateTime desc"
把'%"+@keyword+"%'看成一起
直接写在存储过程中 select * from ProductInfowhere ProductName like '%'+@keyWords+'%'

七.使用SQL存储过程返回多结果集怎么处理
如果有多个结果集返回,那么客户端一定要用一个DataSet来接收才行,这样可以通过DataSet的.Tables来分别访问它返回的数据集了.
也可以用output
DataTable dt = ds.tables[2]
dt.rows[0]["newsId"].tostring

八.如何一次插入多个记录
insert into
OrderDetail
select
@orderId,ShoppingCart.ProductId,ShoppingCart.Quantity,Product.ProductPrice
from
ShoppingCart inner join
Product on ShoppingCart.ProductId=Product.ProductId
where
cartId=@cartId

九.求两个字段的值的积,然后再求和
cast(sum(OrderDetail.Quantity*OrderDetail.UnitCost) as money) as OrderTotal

十.定义为char类型的缺点:有空字符串
解决方法:
经过高手指点,才知道原来红色的代码有问题,interbase数据库如果某个字段是char类型的数据,才存放数据后会自动在字符串后面补上空格,以满足位数需要,因此表面上看,取到的密码和我的输入密码一样,实际上是不一样的。
解决办法:
办法1 if ibt_user_pass.FieldByName('passwd').AsString=edit2.Text then 这句话变成if trim(ibt_user_pass.FieldByName('passwd').AsString)=edit2.Text then
trim函数作用是去掉字符串中多加上去的空格
办法2 数据库的char类型改成varchar类型

十一。在程序中使用存储过程
SqlCommand cmd =new SqlCommand("proGetEmpPassword", cn);
cmd.CommandType = CommandType.StoredProcedure;

SqlParameter paramLoginName=new SqlParameter("@LoginName", SqlDbType.Char, 20);
paramLoginName.Value = strLoginName;
cmd.Parameters.Add(paramLoginName);

SqlParameter paramPassword=new SqlParameter("@Pword", SqlDbType.VarChar, 50);
paramPassword.Direction = ParameterDirection.Output;
cmd.Parameters.Add(paramPassword);

SqlParameter paramReturn=new SqlParameter("@ReturnValue", SqlDbType.Int);
paramReturn.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(paramReturn);//在存储过程中为return @@rowcount,用 来判断,区别select @orderId=@@identity

string arPword ;

try
{
cn.Open();

cmd.ExecuteNonQuery();

if (Convert.ToInt32(paramReturn.Value) == 1)

arPword = (paramPassword.Value).ToString();
else

return null;

}
catch
{
return null;
}
finally
{
if (cn.State == ConnectionState.Open)
cn.Close();
}

return arPword;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐