Python>>SQL I only write copy and paste

introduce

        It is too tiring to write too many sql fields to check and write, and the company’s projects are tight. There are more than 3,000 lines of sql in a week, and various conversions are required to call various interfaces. Therefore, in order to improve work efficiency and gain more time (fishing), I will I have used python , compared to other repeated knocking partners, I will fly directly, and now I will show you the code that I commonly use to write sql

1. Field alias


If you are still manually assigning and pasting table aliases, you will be tired. I will directly backhand a regular

import re

table_AS = 'td.'
schema = '[dbo].'
SQL = f"""SELECT {table_AS}Id,CreateTime,shenpibianma,xingming,gonghao,bumen,shenpizhuangtai,wanchengshijian,zhuti,feiyongbaoxiaozonge,beizhu,fujian
"""
print(re.sub(',', f',{table_AS}', str(SQL), SQL.count(',')))

operation result:


SELECT td.Id,td.CreateTime,td.shenpibianma,td.xingming,td.gonghao,td.bumen,td.shenpizhuangtai,td.wanchengshijian,td.zhuti,td.feiyongbaoxiaozonge,td.beizhu,td.fujian

The sub in the re module is similar to the string function replace to match and replace

Syntax re.sub(pattern, repl, string, count);

pattern: the pattern string in regular, repl: the string to be replaced, string: the original string, count: how many times to replace

And str.count(',') counts the number of comma occurrences, and then corresponds to the number of replacements of the sub function

2. CASE WHEN batch conversion


data_value = "我是谁,ice,_,Seattle"
field_name = 'Demo_test'
data_value = data_value.split(',')
index_range = len(data_value)
sql = ['']


def case_when():
    for i in range(0, index_range - 1):
        sql.append('')
    for i in range(0, index_range, 1):
        sql[i] = f"""    WHEN {field_name} = '{i}' THEN '{data_value[i]}' \n"""
    return ''.join(map(str, sql))

operation result:


CASE
    WHEN Demo_test = '0' THEN '我是谁' 
    WHEN Demo_test = '1' THEN 'ice' 
    WHEN Demo_test = '2' THEN '_' 
    WHEN Demo_test = '3' THEN 'Seattle' 
ELSE '请选择' END Demo_test,

I think it is very convenient, it is very convenient, and it is more convenient to combine. For special cases, such as or or and in case when,

PATINDEX('%[^0-9|.|-|+]%', field)=0 THEN (SELECT Name FROM Areas where ID = field) 

 can be changed according to the specific situation

3. Generate table names and field name series in batches


Realize the logic, query all table names and field names in the system through sql statements, format the output into the required format for output, the regularity used here, where /..../g means full-text matching, the sql used here server

Which uses

SELECT NAME FROM SYSOBJECTS WHERE XTYPE='u' Get all table names in the database

select name from syscolumns where id=(select max(id) from sysobjects where xtype='u' and name = 'data table') to get all the field names of the looked-up table

import re
import pymssql

server = '192.168.10.10'
user = "账号"
password = "密码"
database = "数据库"
connect = pymssql.connect(server, user, password, database)
cursor = connect.cursor()
cursor.execute("select name from sysobjects where xtype='u'")
# print(cursor.fetchall())

Data_Tab = cursor.fetchall()
data_table = re.sub('[/\\[\\](,)\'*/g]', f'', str(Data_Tab))
print(re.sub('[/ /g]', f'\n', str(data_table)))
'''
for i in range(0, len(list_data)):
    print(list_data[i])
'''
# 获取指定表列名
cursor.execute("select name from syscolumns where id=(select max(id) from sysobjects where xtype='u' and name = 'Areas')")
Data_Col = cursor.fetchall()
data_column = re.sub('[/\\[\\]()\'*/g]', f'', str(Data_Col))
print(data_column.replace(',,', ','))

 The results of the operation are as follows. There are many data tables and only some of them are listed.


RF_ProramButton
RF_ProramExport
RF_ProramField
RF_ProramQuery
RF_ProramValidate
RF_SystemButton
RF_Test
RF_Test1Sub
RF_TestSub
RF_UserFileShare
RF_UserShortcut
RF_Vote
RF_VoteItem
RF_VoteItemOption
RF_VotePartakeUser
RF_VoteResult
RF_VoteResultUser
RF_WorkDate
RF_WorkGroup
RF_DbConnection

ID, ParentId, ReionId, Name, MererName, ShortName, MererShortName, LevelType, CityCode, ZipCode, Pinyin, Jianpin, FirstChar, Ln, Lat, Remark, Order, IsDelete, InsertTime,

In this way, it will be very fast in writing the program corresponding to the SQL field, and it can be flexibly matched with other small programs

4. Numbers in quotation marks


def use_re(e):
    value = int(e.group('value'))
    return f"'{str(value)}'"


sql = """
case 
when Staff_Category = 1 then '请选择' 
when Staff_Category = 2 then '试用期员工' 
when Staff_Category = 3 then '正式员工'
when Staff_Category = 5 then '劳务(全职)' 
when Staff_Category = 6 then '劳务(兼职)'
when Staff_Category = 7 then '岗位外包'  
when Staff_Category = 9 then '劳务(临时工)' 
when Staff_Category = 10 then '返聘'  
when Staff_Category = 11 then '特聘' 
else '' end Staff_Category
"""

elements = re.sub('(?P<value>\\d+)', use_re, ''.join(map(str, sql)), count=0, flags=0)
print(f'{elements}')

The regular \d matches the number type, which is represented by \\d in pycharm. Paste the sql in the sql area to add quotation marks to the numbers in batches, which is useful for the type conversion of the front and back ends

The result of the operation is as follows


case 
when Staff_Category = '1' then 'Please choose' 
when Staff_Category = '2' then 'probationary staff' 
when Staff_Category = '3' then 'regular staff'
when Staff_Category = '5' then 'labor (full-time)' 
when Staff_Category = '6' then 'Labor (part-time)'
when Staff_Category = '7' then 'job outsourcing'  
when Staff_Category = '9' then 'labor (temporary)' 
when Staff_Category = '10' then 're-employment'  
when Staff_Category = ' 11' then 'special appointment' 
else '' end Staff_Category

5. Multi-value interception of sql field


In the database, you will encounter a field that stores values ​​of 1, 3, 2, etc. It is not friendly for the case when output display to judge whether it is ('1', '2', '3') on the system, and stuff ( ) can't solve this situation, you need to use substring() in combination with charindex(), where

CHARINDEX(substring, string [, start_location]) 

substring is the string to be searched, string is the string to be searched, the data table field used here

        The start_location parameter is optional, which is the starting location of the search

For this kind of problem, I wrote the case of interception judgment in (range)

import re


def use_re(e):
    value = int(e.group('value'))
    return f"'{str(value)}'"


field = 'seal'  
values = '2,4,7,8'
index_range = 1
sql = ['']
for i in range(0, len(values) - 1):
    sql.append('')
for i in range(0, len(values), 2):
    sql[i] = f"""SUBSTRING({field}, charindex({values[i]},{field}), {index_range}) not in ({values}) AND \n"""


elements = re.sub('(?P<value>[2-9]+)', use_re, ''.join(map(str, sql)), count=0, flags=0)
print(f'{elements}')

The operation effect is as follows


SUBSTRING(seal, charindex('2',seal), 1) not in ('2','4','7','8') AND 
SUBSTRING(seal, charindex('4',seal), 1) not in ('2','4','7','8') AND 
SUBSTRING(seal, charindex('7',seal), 1) not in ('2','4','7','8') AND 
SUBSTRING(seal, charindex('8',seal), 1) not in ('2','4','7','8') AND 

The above are the five commonly used small modules, which will be written on the graphical interface later

Guess you like

Origin blog.csdn.net/qq_53521409/article/details/128527245