Removing on the basis of condition

£可爱£侵袭症+ 提交于 2019-12-23 19:12:27

问题


I was trying to create a query loop, which does interactive steps from one instance to the next. After fetching the right data

I have connected it with database


I am able to run but I want to apply the cases on basis of datypes that if the COL_NAMES datatype is varchar then '' and if the COL_NAME datatype is float or int then replace it with 0 and for datetime datatye replace it with 1880-10-10 now I am able to apply only on blank on datatypes:

  a = ','.join(f"[{y}]=isnull([{y}], '')" for y in COL_NAMES)
  a

Mine query is like

  z = f"[UPDATE ABC_A SET {a}]

回答1:


You're already looping through the results from the SELECT, so instead of storing DATA_TYPE in a separate list you could just store the COLUMN_NAME and its corresponding default value in a dict. You could then glue together the [column_name]=isnull([column_name, ... fragments and insert them into your UPDATE statement:

sql = """\
SELECT COLUMN_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'ABC_A'"""
column_defaults = {}
for row in crsr.execute(sql):
    if row.DATA_TYPE in ['varchar', 'nvarchar']:
        default_value = "''"
    elif row.DATA_TYPE in ['int', 'float']:
        default_value = "0"
    elif row.DATA_TYPE in ['date', 'datetime2']:
        default_value = "'1880-10-10'"
    else:
        raise ValueError(f"Unhandled column type: {row.DATA_TYPE}")
    column_defaults[row.COLUMN_NAME] = default_value
s = ', '.join([f"[{col}]=isnull([{col}], {column_defaults[col]})" for col in column_defaults])
print(s)
# [Date]=isnull([Date], '1880-10-10'), [NAME]=isnull([NAME], ''), [FileNo]=isnull([FileNo], 0)
sql = f"UPDATE ABC_A SET {s}"
print(sql)
# UPDATE ABC_A SET [Date]=isnull([Date], '1880-10-10'), [NAME]=isnull([NAME], ''), [FileNo]=isnull([FileNo], 0)

This is just an example, so you may need to add more column types to theif/elif/else block.



来源:https://stackoverflow.com/questions/57340041/removing-on-the-basis-of-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!