Home Database Mysql Tutorial 在论坛中出现的比较难的sql问题:17(字符分拆2)

在论坛中出现的比较难的sql问题:17(字符分拆2)

Jun 07, 2016 pm 03:22 PM
sql Appear character forum question

最近,在论坛中,遇到了不少比较难的sql问题,虽然自己都能解决,但发现过几天后,就记不起来了,也忘记解决的方法了。 所以,觉得有必要记录下来,这样以后再次碰到这类问题,也能从中获取解答的思路。 1、存储过程 表A: aid bid status 1 1 0 1 2 0 2 1 0

最近,在论坛中,遇到了不少比较难的sql问题,虽然自己都能解决,但发现过几天后,就记不起来了,也忘记解决的方法了。

所以,觉得有必要记录下来,这样以后再次碰到这类问题,也能从中获取解答的思路。

1、存储过程

表A:
aid bid status
1 1 0
1 2 0
2 1 0
1 111 0
11 11 0

每条数据aid 联合bid 是唯一的,如何写存储过程进行批量操作。

传入[{aid:1,bid:2},{aid:11,bid:11}]
查询出下表数据:

aid bid status
1 2 0
11 11 0

建表语句:

CREATE TABLE A
(aid      INT,
 bid      INT,
 statuss  INT 
)

INSERT A 
SELECT 1,1,0 UNION ALL
SELECT 1,2,0 UNION ALL            
SELECT 2,1,0 UNION ALL
SELECT 1,111,0 UNION ALL
SELECT 11,11,0
go
Copy after login
--1.字符串分拆函数
if exists(select * from sys.objects where name = 'f_splitSTR' and type = 'tf')
   drop function dbo.f_splitSTR
go

create function dbo.f_splitSTR
(
	@s varchar(8000),     --要分拆的字符串
	@split varchar(10)    --分隔字符
) 
returns @re table(                      --要返回的临时表
                     col varchar(1000)  --临时表中的列 
                 )
as
begin   
  declare @len int
  
  set @len = LEN(@split)      --分隔符不一定就是一个字符,可能是2个字符
  
  while CHARINDEX(@split,@s) >0
  begin
	insert into @re 
	values(left(@s,charindex(@split,@s) - 1))
	
	set @s = STUFF(@s,1,charindex(@split,@s) - 1 + @len ,'')    --覆盖:字符串以及分隔符
  end
  
  insert into @re values(@s)
  
  return   --返回临时表
end
go  

CREATE PROC dbo.Pro_A
@param varchar(100)
AS 

declare @str varchar(100)
declare @sql nvarchar(4000)

set @str = ''
set @sql = ''

if OBJECT_ID('tempdb..#temp') is not null
   drop table #temp


--把拆分后的字段,插入到临时表
select LEFT(col,charindex(',',col)-1) as aid,
       SUBSTRING(col,charindex(',',col)+1,LEN(col)) as bid
       into #temp
from dbo.f_splitSTR(@param,';') t


--生成动态语句
set @sql = 'SELECT * 
            FROM A
            WHERE exists(select 1 from #temp 
                         where #temp.aid = a.aid and #temp.bid = a.bid)'

exec(@sql)
go


exec Pro_A '1,2;11,11'
/*
aid	bid	statuss
1	2	0
11	11	0
*/
Copy after login

另一种方法:
if object_id('dbo.Pro_A') is not null
   drop proc Pro_A
go

create PROC dbo.Pro_A
@param varchar(100)
AS 

declare @str varchar(100)
declare @sql nvarchar(4000)

set @str = @param
set @sql = ''

set @str = replace(replace(replace(replace(REPLACE(@str,'[',''),']',''),'},{',';'),
                   '{',''),'}','')
             
set @str = 'select '+replace(replace(@str,';',' union select '),':','=')


if OBJECT_ID('tempdb..#temp') is not null
   drop table #temp

CREATE TABLE #temp
(aid      INT,
 bid      INT)

--把数据插入到临时表中
insert into #temp(aid,bid)
exec(@str)


--生成动态语句
set @sql = 'SELECT * 
            FROM A
            WHERE exists(select 1 from #temp 
                         where #temp.aid = a.aid and #temp.bid = a.bid)'

exec(@sql)

--print @str
go


exec Pro_A '[{aid:1,bid:2},{aid:11,bid:11}]'
/*
aid	bid	statuss
1	2	0
11	11	0
*/
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the difference between HQL and SQL in Hibernate framework? What is the difference between HQL and SQL in Hibernate framework? Apr 17, 2024 pm 02:57 PM

HQL and SQL are compared in the Hibernate framework: HQL (1. Object-oriented syntax, 2. Database-independent queries, 3. Type safety), while SQL directly operates the database (1. Database-independent standards, 2. Complex executable queries and data manipulation).

Usage of division operation in Oracle SQL Usage of division operation in Oracle SQL Mar 10, 2024 pm 03:06 PM

"Usage of Division Operation in OracleSQL" In OracleSQL, division operation is one of the common mathematical operations. During data query and processing, division operations can help us calculate the ratio between fields or derive the logical relationship between specific values. This article will introduce the usage of division operation in OracleSQL and provide specific code examples. 1. Two ways of division operations in OracleSQL In OracleSQL, division operations can be performed in two different ways.

Comparison and differences of SQL syntax between Oracle and DB2 Comparison and differences of SQL syntax between Oracle and DB2 Mar 11, 2024 pm 12:09 PM

Oracle and DB2 are two commonly used relational database management systems, each of which has its own unique SQL syntax and characteristics. This article will compare and differ between the SQL syntax of Oracle and DB2, and provide specific code examples. Database connection In Oracle, use the following statement to connect to the database: CONNECTusername/password@database. In DB2, the statement to connect to the database is as follows: CONNECTTOdataba

Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Feb 26, 2024 pm 07:48 PM

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

How to solve the 5120 error in SQL How to solve the 5120 error in SQL Mar 06, 2024 pm 04:33 PM

Solution: 1. Check whether the logged-in user has sufficient permissions to access or operate the database, and ensure that the user has the correct permissions; 2. Check whether the account of the SQL Server service has permission to access the specified file or folder, and ensure that the account Have sufficient permissions to read and write the file or folder; 3. Check whether the specified database file has been opened or locked by other processes, try to close or release the file, and rerun the query; 4. Try as administrator Run Management Studio as etc.

Database technology competition: What are the differences between Oracle and SQL? Database technology competition: What are the differences between Oracle and SQL? Mar 09, 2024 am 08:30 AM

Database technology competition: What are the differences between Oracle and SQL? In the database field, Oracle and SQL Server are two highly respected relational database management systems. Although they both belong to the category of relational databases, there are many differences between them. In this article, we will delve into the differences between Oracle and SQL Server, as well as their features and advantages in practical applications. First of all, there are differences in syntax between Oracle and SQL Server.

Discuz Forum Permission Management: Read Permission Setting Guide Discuz Forum Permission Management: Read Permission Setting Guide Mar 10, 2024 pm 05:33 PM

Discuz forum permission management: Read the permission setting guide In Discuz forum management, permission setting is a crucial part. Among them, the setting of reading permissions is particularly important, as it determines the scope of content that different users can see in the forum. This article will introduce in detail the reading permission settings of the Discuz forum and how to flexibly configure it for different needs. 1. Basic concepts of reading permissions In the Discuz forum, reading permissions mainly include the following concepts that need to be understood: Default reading permissions: Default after new user registration

The difference between Oracle and SQL and analysis of application scenarios The difference between Oracle and SQL and analysis of application scenarios Mar 08, 2024 pm 09:39 PM

The difference between Oracle and SQL and analysis of application scenarios In the database field, Oracle and SQL are two frequently mentioned terms. Oracle is a relational database management system (RDBMS), and SQL (StructuredQueryLanguage) is a standardized language for managing relational databases. While they are somewhat related, there are also some significant differences. First of all, by definition, Oracle is a specific database management system, consisting of

See all articles