简体   繁体   中英

Removing spaces and returning multiple rows in sql

So Im trying to do a fuzzy search on users and return their names and emails. For some mad reason whoever made this database decided to make the email column a nchar(320). So I need to remove the spaces from the email. I was able to do it. But the way I did it only returns single variables. Im not sure how to get it to return entire columns with the spaces removed from the email addresses. Heres what I have now.

USE [TADB]
GO
/****** Object:  StoredProcedure [dbo].[ResourceSearch]    Script Date: 05/01/2015 14:29:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[ResourceSearch]
@Name varchar(25) = null    

AS
BEGIN

    DECLARE @Email varchar(100)
    DECLARE @ResName varchar(100)

    IF @Name = '' OR @Name IS NULL
        Set @Name = NULL
    Else
        Set @Name = @Name + '%' 

    SELECT @Email = EMAIL_ADDRESS 
    FROM [RESOURCE]
    WHERE 
        (@Name IS NULL OR (RESOURCE_NAME LIKE @Name))

    SELECT @ResName = RESOURCE_NAME
    FROM [RESOURCE]
    WHERE 
        (@Name IS NULL OR (RESOURCE_NAME LIKE @Name))

    SELECT @ResName, REPLACE(@Email, ' ', '')

END

You can replace the last 3 SELECT statements with this to display all columns with the whitespaces removed from the email:

SELECT RESOURCE_NAME, REPLACE(EMAIL_ADDRESS, ' ', '')
FROM [RESOURCE]
WHERE 
    (@Name IS NULL OR (RESOURCE_NAME LIKE @Name))

You are only getting single variables because you are setting the first value from the result into a variable, while just selecting on that column will return the entire result.

Also, when the select statements have the same FROM/WHERE clauses with conditions you can combine the 2 statements into 1 and set the variables separately. But in this case it looks like you don't need the @Email and @ResName variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM