Make a SQL Server process by receiving a special character string and getting only the numbers

Asked

Viewed 204 times

2

Hello, I have a system developed in ASP Classic, in which I select up to 5 times on a screen. These times are sent to the other page via querystring, but the format that comes is followed by an exclamation. Example 7!10! 19! What I need to do is take these codes (7, 10 and 19) and use them to insert a record into an SQL Server table with each of them.

I am trying to do this via Project, because my knowledge in ASP is very small.

Someone could give me a light?

  • If you are interested in knowing other approaches to separate the numbers, I suggest reading the article "Separating multi-valued text content (split string)". Access https://portosql.wordpress.com/2019/01/27/separar-textualcontent_multivalorado_string-split/

1 answer

0


First create a function to split your string into separate values:

CREATE FUNCTION dbo.splitstring ( @separador CHAR, @stringToSplit VARCHAR(MAX) )
  RETURNS
  @returnList TABLE ([Name] [nvarchar] (500))
AS
BEGIN

  DECLARE @name NVARCHAR(255)
  DECLARE @pos INT

  WHILE CHARINDEX(@separador, @stringToSplit) > 0
    BEGIN
    SELECT @pos  = CHARINDEX(@separador, @stringToSplit)  
    SELECT @name = SUBSTRING(@stringToSplit, 1, @pos-1)

    INSERT INTO @returnList 
    SELECT @name

    SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos+1, LEN(@stringToSplit)-@pos)
 END

 INSERT INTO @returnList
 SELECT @stringToSplit

 RETURN
END

Call the created function by passing a string containing the values separated by "!":

SELECT * FROM dbo.splitstring('!', '91!12!65!78!56!789')

The result for this query will be below:

inserir a descrição da imagem aqui

To insert the values in your other table, simply adapt the following command according to the columns you have in your table:

INSERT INTO TabelaDeDestino SELECT Name FROM dbo.splitstring('!', '91!12!65!78!56!789')

This is an adaptation of the answer in English https://stackoverflow.com/questions/10914576/t-sql-split-string

  • Thank you very much Ulysses! Help me too!!!! D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.