搜索两个表中的所有列的SQL查询,我需要向其添加另一列“AS”

时间:2013-07-11 10:20:50

标签: sql-server tsql

下面是我的SQL查询,它搜索两个表中的所有列(我没有这样做)我需要将此语句添加到它

, (tblUsers.Forename + ' ' + tblUsers.Surname) AS CleanName

但我不确定在哪里放,有人可以帮帮我吗? 感谢

USE [ITAPP]
GO
/****** Object:  StoredProcedure [dbo].[sp_SearchAllTables]    Script Date: 07/11/2013 10:57:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROC [dbo].[sp_SearchAllTables]
(
    @SearchStr nvarchar(255)
)
AS
BEGIN

declare @where varchar(8000)
declare @sql varchar(8000)
set @sql = 'select * from tblUsers u join tblEquipment e on e.userid = u.id WHERE 1 = 1 AND ( 1= 0 '

select @where = coalesce(@where ,'' ) + ' OR  ' + case when object_name(object_id)  = 'tblUsers' then 'u' else 'e' end + '.[' +  name + '] LIKE ''%' + replace(@SearchStr, '''', '''''') + '%'' '
 from sys.columns where object_id in ( select object_id from sys.objects where name in ( 'tblUsers','tblEquipment' ))
 and collation_name is not null
set @where = coalesce(@where, '') + ')'

print @sql
print @where

exec(@sql + @where)

END 

2 个答案:

答案 0 :(得分:3)

变化:

set @sql = 'select * from tblUsers u join tblEquipment e on e.userid = u.id WHERE 1 = 1 AND ( 1= 0 '

set @sql = 'select u.*,e.*, (u.Forename + '' '' + u.Surname) AS CleanName from tblUsers u join tblEquipment e on e.userid = u.id WHERE 1 = 1 AND ( 1= 0 '

注意:您需要分隔单引号..

答案 1 :(得分:3)

您只是在set @sql line

上添加语句的select部分

这里填写了。

USE [ITAPP]
GO
/****** Object:  StoredProcedure [dbo].[sp_SearchAllTables]    Script Date: 07/11/2013 10:57:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROC [dbo].[sp_SearchAllTables]
(
    @SearchStr nvarchar(255)
)
AS
BEGIN

declare @where varchar(8000)
declare @sql varchar(8000)
set @sql = 'select u.*, e.*, (tblUsers.Forename + '' '' + tblUsers.Surname) AS CleanName from tblUsers u join tblEquipment e on e.userid = u.id WHERE 1 = 1 AND ( 1= 0 '

select @where = coalesce(@where ,'' ) + ' OR  ' + case when object_name(object_id)  = 'tblUsers' then 'u' else 'e' end + '.[' +  name + '] LIKE ''%' + replace(@SearchStr, '''', '''''') + '%'' '
 from sys.columns where object_id in ( select object_id from sys.objects where name in ( 'tblUsers','tblEquipment' ))
 and collation_name is not null
set @where = coalesce(@where, '') + ')'

print @sql
print @where

exec(@sql + @where)

END 

可能值得阅读SQL教程,以便您了解其工作原理: 下面是一个例子:http://www.w3schools.com/sql/sql_select.asp