前几天做的几道题,比较基础。感觉还不错拿出来分享一下,欢迎拍砖
1.
Create Table TableXml(id int identity(1,1) Primary Key,x xml)
Go
Insert Into TableXml
Select
'<root>
<Info id="1" name="Name1" City="City1"/>
<Info id="2" name="Name2" City="City2"/>
<Info id="3" name="Name3" City="City3"/>
</root>'
Union Select
'<root>
<Info id="4" name="Name4" City="City4"/>
<Info id="5" name="Name5" City="City5"/>
<Info id="6" name="Name6" City="City6"/>
</root>'
Go
--问题:如何把<Info id="1" name="Name1" City="City1"/> 更新成 <Info id="1" name="NewName" City="NewCity"/>
--方法比较笨
--应该有比较好的吧,可是我没想到
declare @NewName varchar(20)
declare @NewCity varchar(20)
declare @ID int
select @NewName='NewName',@NewCity='NewCity',@id=1
update TableXml
set x.modify('
replace value of (/root/Info[@id=sql:variable("@ID")]/@name)[1]
with sql:variable("@NewName")
'
);
update TableXml
set x.modify('
replace value of (/root/Info[@id=sql:variable("@ID")]/@City)[1]
with sql:variable("@NewCity")
'
)
select * from TableXml
--2.在SQL查询语句(Select Distinct... From ... Join ... On ... Where ... Group By ... With ... Having ... Order By ...)中,各个步骤是按什么先后顺序执行的?
-- 同時,Where 条件中三个关键字(Or, And, Not),它们搜索的順序是什么?
--执行顺序
1、FROM
2、on
3、join--做笛卡尔乘积
4、WHERE
5、group BY
6、with(cube | rollup )
7、HAVING
8、select 列表
9、DISTINCT
10、order by
--当然后很多特殊的。
3.如何比较两个存储过程是否一致?
;with t as(
select count(b.definition) as cnt
from sys.objects As a
Inner Join sys.sql_modules As b On b.object_id=a.object_id
where a.is_ms_shipped=0 And a.type='P' and name in('p1','p2')
)
select case when cnt=1 then'一致' else '不一致' end from t
--这题主要是自己想象,比如:除內容外,有时间等信息的判斷
4.根据某个字段,如何查詢到对应的表和字段及数据库?
如,給出值"798DACD1-8160-45FF-B3E4-9F4840578CDB",要求查詢出"798DACD1-8160-45FF-B3E4-9F4840578CDB"所在的表名,字段名,数据库名.
--用游标遍历
declare @sql varchar(800)
set @sql='798DACD1-8160-45FF-B3E4-9F4840578CDB' --要搜索的字符串
declare @sql varchar(8000)
declare tablecursor cursor local for
select sql='if exists ( select 1 from ['+ s.name + '].['+o.name+'] where ['+c.name+'] like ''%'+@sql+'%'' )
print ''所在的表及字段:['+o.name+'].['+c.name+']'''
from sys.syscolumns c
join sys.objects o on c.id=o.object_id
join sys.schemas s on o.schema_id = s.schema_id